简体   繁体   English

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

[英]Why is my code running infinitely?

this is an even odd calculator that runs infinitely without any errors. 这是一个偶数奇数计算器,可以无限运行而没有任何错误。 Does anyone know how to fix this? 有谁知道如何解决这一问题? Is it ok for me to call the method with the input from 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)

Just a few things you have wrong, the rest are pretty good, explain are in the comments: 只是您错了几件事,其余的都还不错,请在注释中进行解释:

All the variables in [x, y , even , odd] are useless at all, so that's why I erased them. [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)

you can try it here, and see how do correctly the job :) -> https://repl.it/Nm70/0 您可以在这里尝试一下,看看如何正确完成工作:)-> https://repl.it/Nm70/0

行号5应该是i = i + 1

I'm assuming you have a formatting issue with stackoverflow and not a formatting issue with your actual code. 我假设您在stackoverflow上遇到格式化问题,而在您的实际代码中没有遇到格式化问题。 The lines after your while loop need to be indented which I'm assuming you are doing. while循环后的行需要缩进,我假设您正在这样做。 The problem you have is that you aren't incrementing i. 您的问题是您没有增加i。 The first line after your input you have i + 1. That does nothing as you aren't assigning it to anything. 输入后的第一行为i +1。这无济于事,因为您没有将其分配给任何东西。 You have x += 1 and y += 1 later on in your code which increments and assigns. 稍后在代码中将x + = 1和y + = 1递增并赋值。 So basically change your i+1 line to be i += 1 or i = i + 1 因此,基本上将您的i + 1行更改为i + = 1或i = i + 1

Everything that you want in the while loop needs to be indented by one "tab" like so: 在while循环中,您想要的所有内容都需要用一个“制表符”缩进,如下所示:

while i <= time:
    #Code goes here

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

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