【问题标题】:I want to repeat a function indefinitely [duplicate]Python我想无限期地重复一个函数[重复]
【发布时间】:2021-04-22 03:32:28
【问题描述】:

所以我正在做一些关于 python 的练习,我的任务是创建一个可以接受数字的程序,如果它是偶数,则将其除以 2。或者它会取数字,乘以 3,然后加 1。它应该要求输入,然后它应该等待另一个输入。

所以我的代码看起来像这样,请注意我是新手。

print('Please enter a number:')

def numberCheck(c):
        if c % 2 == 0:
            print(c // 2)
        elif c % 2 == 1:
            print(3 * c + 1)
c = int(input())

numberCheck(c)

我希望它只打印一次“请输入一个数字”。但运行后我希望它等待另一个号码。我该怎么做?

我尝试了一个 for 循环,但它使用了一个范围,我不想设置一个范围,除非有办法将它做到无穷大。

感谢您的帮助!

【问题讨论】:

  • 所以,我在想你目前的困境,但我也很好奇。您使用楼层划分是否有原因?
  • while True 是你的朋友。另外,由于您似乎是 Python 初学者,我可以建议使用 PEP8 命名风格吗?即没有camelCase 名称,而是snake_case
  • 我不知道,这只是本书的第 3 章,我正在按照所说的做 lol
  • 如果你使用 Python 3.9 或更高版本,请使用while (c:= int(input()): numberCheck(c) 获得无限循环

标签: python python-3.x


【解决方案1】:

所以我的理解是你希望函数无限期地运行。这是我的方法,通过使用 while 循环

print("Enter a number")

while True:
  c = int(input(""))
  numberCheck(c)

【讨论】:

  • 次要:应该是while True:(大写T)
  • @Slakker 好吧,这不是小事!
  • 工作完美,谢谢。当我尝试 while 循环时,我将 while True 放在了错误的位置,因为我没有得到预期的结果,但现在我明白为什么这会起作用了,
  • 你为什么说它没有内存效率?如果我正确理解垃圾收集,内存不应该在这里累积
  • 那是我的误会
【解决方案2】:

如果你想运行一个无限循环,可以通过一个while循环来完成。

print('Please enter a number:')

def numberCheck(c):
        if c % 2 == 0:
            print(c // 2)
        elif c % 2 == 1:
            print(3 * c + 1)
            
while True:
    c = int(input())
    numberCheck(c)

【讨论】:

    【解决方案3】:

    您可以将while 循环与True 一起使用:

    while True:
        c = int(input())
        numberCheck(c)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-06
      • 2017-07-07
      • 2017-06-18
      • 1970-01-01
      • 1970-01-01
      • 2022-01-15
      • 2019-06-18
      相关资源
      最近更新 更多