简体   繁体   中英

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.

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

行号5应该是i = i + 1

I'm assuming you have a formatting issue with stackoverflow and not a formatting issue with your actual code. The lines after your while loop need to be indented which I'm assuming you are doing. The problem you have is that you aren't incrementing i. The first line after your input you have i + 1. That does nothing as you aren't assigning it to anything. You have x += 1 and y += 1 later on in your code which increments and assigns. So basically change your i+1 line to be i += 1 or i = i + 1

Everything that you want in the while loop needs to be indented by one "tab" like so:

while i <= time:
    #Code goes here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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