Home > Net >  My code got stuck in a forever loop, how do I fix this?
My code got stuck in a forever loop, how do I fix this?

Time:03-19

My code:

answer = input("What would you like to say?")
answer2 = input("How many times?")
while answer2:
    print(answer)

The code should be working but when I type "I like trees" for variable: answer and "2" for variable: answer2, IT'S A FOREVER LOOP!!!!!!!!!

CodePudding user response:

For one, input returns a string and you need an integer. Additionally, a for loop is more appropriate here than a while loop. Try the following:

for i in range(int(answer2)):
    print(answer)

CodePudding user response:

A while loop needs some kind of update. You never update answer2 so if it starts out as being true, your loop will never end.

Assuming answer2 should actually be an integer.

answer = input("What would you like to say?")
answer2 = int(input("How many times?"))

while answer2:
    print(answer)
    answer2 -= 1

Integers are true as long as they are not 0. Each time through we need to subtract 1 from answer2 to bring it eventually down to 0, at which point the loop will break.


Of course, negative numbers will also be true, and subtracting from a negative number will never get you to zero, so it's worth checking the user's input before the loop.

You might want to write a simple function like get_positive_int to provide this assurance that the user's input is greater than or equal to 0.

def get_positive_int(prompt=''):
    while True:
        i = int(input(prompt))
        if i >= 0:
            return i
  • Related