python how to repeat code

两盒软妹~` 提交于 2020-11-24 22:42:21

问题


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 ?

import requests
addr = input()
vendor = requests.get('http://api.macvendors.com/' + addr).text
print(addr, vendor)

回答1:


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`:

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.




回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/42747894/python-how-to-repeat-code

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!