undefined
Fri Mar 29 2024 21:14:37 GMT+0000 (Coordinated Universal Time)
Saved by
@wiseteacher
An infinite loop
It would be easy, but wrong, to write the above code like this:
import random
correct_answer = random.randint(1, 10)
guess = int(input("Guess a number between 1 and 10: "))
while guess != correct_answer:
if guess == correct_answer:
print("Correct!")
else:
print("Wrong :(")
Copy code
Copy And Save
Share
Ask Copilot
Save
That's because we are asking the user for their guess only once, in the beginning, but not inside the loop. When Python returns to repeat the lines inside the loop, none of those ask the user for another guess. The program will keep printing "Wrong :(" over and over again forever.
Here is another infinite loop:
import time
while True:
time.sleep(1)
print("loop")
Copy code
Copy And Save
Share
Ask Copilot
Save
The condition here is simply "True". It is literally (and by design) never false. So the loop will continue forever.
content_copyCOPY
https://www.mathplanet.com/education/programming/logic-and-choice/simple-repetition
Comments