繁体   English   中英

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

[英]Why is my code running infinitely?

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

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)

只是您错了几件事,其余的都还不错,请在注释中进行解释:

[x,y,even,奇数]中的所有变量根本没有用,所以这就是我删除它们的原因。

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

我假设您在stackoverflow上遇到格式化问题,而在您的实际代码中没有遇到格式化问题。 while循环后的行需要缩进,我假设您正在这样做。 您的问题是您没有增加i。 输入后的第一行为i +1。这无济于事,因为您没有将其分配给任何东西。 稍后在代码中将x + = 1和y + = 1递增并赋值。 因此,基本上将您的i + 1行更改为i + = 1或i = i + 1

在while循环中,您想要的所有内容都需要用一个“制表符”缩进,如下所示:

while i <= time:
    #Code goes here

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM