为什么我的代码是运行无限?

Why is my code running infinitely?

这是一个奇数计算器,可以无限运行,没有任何错误。有谁知道如何解决这一问题?我可以用times的输入调用方法吗?

def calc(time):
    i = 1
    while i <= time:
       num = int(input("Enter your number"))
       i + 1
       x=0
       y=0

       if (int(num) % 2 == 0):
          even = True
          print("even")


       elif (int(num) % 2 != 0):
          odd = True
          print("odd")



       if (odd == True):
         x += 1

       elif (even == True):
         y += 1


times = int(input("How many numbers will you be putting in this calc?"))

calc(times)

我假设您遇到的是 Whosebug 的格式问题,而不是您的实际代码的格式问题。你的 while 循环之后的行需要缩进,我假设你正在做。你遇到的问题是你没有增加我。输入后的第一行是 i + 1。这没有任何作用,因为您没有将它分配给任何东西。您稍后在递增和分配的代码中有 x += 1 和 y += 1 。所以基本上将 i+1 行更改为 i += 1 或 i = i + 1

while 循环中的所有内容都需要缩进一个 "tab",如下所示:

while i <= time:
    #Code goes here

只是你说的不对,其他的都很好,在评论中解释:

[x, y , even , odd] 中的所有变量都没有用,所以我删除了它们。

def calc(time):
    i = 1
    while i <= time:
      num = int(input("Enter your number"))
      i+=1 # important thing here, to update the value the symbol is +=, not just +

      if (int(num) % 2 == 0):
          print("even")

      else: # there is no need of elif, if the number is not even, by definition, it is odd
          print("odd")

times = int(input("How many numbers will you be putting in this calc?"))

calc(times)

您可以在这里尝试一下,看看如何正确完成这项工作:) -> https://repl.it/Nm70/0

第 5 行应该是 i = i+1