【问题标题】:How do I write a loop to repeat the code?如何编写循环来重复代码?
【发布时间】:2017-03-12 13:18:31
【问题描述】:

我是 Python 的初学者,我想重复这段代码。但是如果没有“goto”,我真的不知道该怎么做。我试图了解循环,但不明白如何应用它们。

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

【问题讨论】:

标签: python loops


【解决方案1】:

创建一个函数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 中不可用。这会导致很多问题。

【讨论】:

    【解决方案2】:

    循环是实现这一目标的最佳方式。例如看看这个伪代码:

    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
    

    【讨论】:

      【解决方案3】:

      你可以创建一个变量,然后说只要这个变量的值是真的,就重复for循环中的代码。

      【讨论】:

        猜你喜欢
        • 2017-09-11
        • 1970-01-01
        • 2021-09-25
        • 1970-01-01
        • 2021-07-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-04
        相关资源
        最近更新 更多