[英]How do I write a loop to repeat the code?
我是 Python 的初学者,我想重复这段代码。 但是如果没有“goto”,我真的不知道该怎么做。 我试图了解循环,但不明白如何应用它们。
import requests
addr = input()
vendor = requests.get('http://api.macvendors.com/' + addr).text
print(addr, vendor)
创建一个函数repeat
并在其中添加您的代码。 然后使用while True
无限调用它或for i in range(6)
调用它 6 次:
import requests
def repeat():
addr = input()
vendor = requests.get('http://api.macvendors.com/' + addr).text
print(addr, vendor)
while True:
repeat()
请注意,不建议在任何语言中使用 goto,并且在 python 中不可用。 它会导致很多问题。
循环是实现这一目标的最佳方式。 例如查看这个伪代码:
While person is hungry
Eat food a bite of food
Increase amount of food in stomach
If amount of food ate fills stomach
person is no longer hungry
stop eating food
在代码中,这看起来像这样:
food_in_stomach = 0
while food_in_stomach <= 8:
eat_bite_of_food()
food_in_stomach += 1
因此,您可以像下面这样实现您的代码:
times_to_repeat = 3
while times_to_repeat > 0:
addr = input()
vendor = requests.get('http://api.macvendors.com/' + addr).text
print(addr, vendor)
times_to_repeat -= 1
你可以创建一个变量,然后说只要这个变量的值是真的,就重复for循环中的代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.