python如何重复代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42747894/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
python how to repeat code
提问by Michal
I am a very beginner in python and I want to repeat this code. But I dont't really know how to do this without "goto". I tried to learn about loops for hours but still no sucess. Any ideas ?
我是 python 的初学者,我想重复这段代码。但我真的不知道如何在没有“goto”的情况下做到这一点。我尝试学习了几个小时的循环,但仍然没有成功。有任何想法吗 ?
import requests
addr = input()
vendor = requests.get('http://api.macvendors.com/' + addr).text
print(addr, vendor)
回答by Emin Mastizada
Create a function repeat
and add your code in it. Then use while True
for infinite call or for i in range(6)
for 6 times call`:
创建一个函数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()
Note that goto is not recommended in any language and is not available in python. It causes a lot of problems.
请注意,任何语言都不推荐使用 goto,并且在 python 中不可用。它会导致很多问题。
回答by Christopher Reece
A loop is the best way to achieve this. For example check out this pseudo code:
循环是实现这一目标的最佳方式。例如查看这个伪代码:
// 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
In code this would look something like this:
在代码中,这看起来像这样:
food_in_stomach = 0
while food_in_stomach <= 8:
eat_bite_of_food()
food_in_stomach = food_in_stomach + 1
You could therefore implement your code like the following:
因此,您可以像下面这样实现您的代码:
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
回答by Jacob Riplow
You can create a variable, and then say that as long as the variable is true to its value, to repeat the code in the for loop.
你可以创建一个变量,然后说只要变量的值是真的,就重复for循环中的代码。