'Why is it that this one change in my code did not allow the while loop to go on forever?
i have an awfully simple and obtuse question, i hope this is the right place to ask this:
i wrote a program that generates two random integers, adds them together and prompts the user for an answer. if the user gets it wrong the question is prompted again until they get it right-- this is where the while loop comes into play and so i implemented it like this:
import random
number1 = random.randint(0, 99)
number2 = random.randint(0, 99)
answer = eval(input("What is {numberA} + {numberB}? ".format(numberA=number1, numberB=number2)))
check = answer == number1 + number2
if answer == number1 + number2:
print("{numberA} + {numberB} = {Answer}".format(numberA=number1, numberB=number2, Answer=answer))
while answer != number1 + number2:
eval(input("That's not right. Try again: "))
print("yes that is right")
what ended up happening instead was that while loop ended up going on forever, when i instead changed the while statement to this:
while answer != number1 + number2:
answer = eval(input("That's not right. Try again: "))
it worked and the print statement that followed it was executed it immediately. what i don't understand was why did my mistake make the loop go on for infinity? how does redefining the answer variable in that statement make the while loop condition false?
Solution 1:[1]
In your erroneous version, answer never changes, so once your code enters the loop (because answer != number1 + number2) the condition remains true forever.
Solution 2:[2]
You never modified answer in your original code. If the condition existed where the loop would start, nothing ever changed the state so that the test would fail and the loop would end.
Solution 3:[3]
import random
number1 = random.randint(0, 99)
number2 = random.randint(0, 99)
correct_answer = number1 + number2
answer = int(input("What is {numberA} + {numberB}? ".format(numberA=number1, numberB=number2)))
while answer != number1 + number2:
answer = int(input("That's not right. Try again: ".format(numberA=number1, numberB=number2)))
if answer == correct_answer:
break
print("yes that is right")
Solution 4:[4]
answer never changes, you can fix this by simply adding
if answer == correct_answer:
break
in the
while answer != number1 + number2:
loop.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | kindall |
| Solution 2 | Chris |
| Solution 3 | alvrm |
| Solution 4 | BTheOne |
