Repeating with while True
So far every line of a program has run at most once. But programs often need to do the same thing many times: ask for one more number, play one more round. A loop repeats a block of code. The simplest loop in Python is while True, and the command break ends it:
while True:
word = input("Say something (bye to quit): ")
if word == "bye":
break
print(f"You said: {word}")
print("Goodbye!")
hello
loops are fun
byeSay something (bye to quit): hello
You said: hello
Say something (bye to quit): loops are fun
You said: loops are fun
Say something (bye to quit): bye
Goodbye!Here is how it works:
while True:starts the loop, and the indented lines after it are the loop's block.- When Python gets to the end of the block, it jumps back to the
whileline and runs the block again. One run through the block is called an iteration. breakends the loop at once. Python goes on from the first line after the loop's block, here theprint("Goodbye!").
The break is inside an if, so the loop ends only when the user types bye. On that iteration the last line of the block never runs, because the loop has already ended.
A loop that never ends
If no break can ever run, the loop goes on forever. This is called an infinite loop. This one should stop when the user types 0, but it never does:
while True:
answer = input("Play another round? (1 = yes, 0 = no) ")
if answer == 0:
break
print("Here we go again!")
input returns a string, so when the user types 0, answer is the string "0", not the number 0, and "0" == 0 is false. The condition can never be true, so whatever the user types, the loop asks again, forever. The fix is to compare with a string, answer == "0", or to convert the answer with int first. Every while True loop needs a break that will run sooner or later. (A loop that doesn't wait for input and never reaches its break keeps running as fast as it can; on this site, a program that runs for more than a few seconds is stopped.)
Asking until the answer is acceptable
A loop is also the way to ask again until the user types something the program can use:
while True:
age = int(input("Your age: "))
if age >= 0:
break
print("An age can't be negative. Try again.")
print(f"Thanks! You are {age}.")
-5
31Your age: -5
An age can't be negative. Try again.
Your age: 31
Thanks! You are 31.Notice the order inside the loop: read the input, stop if it's fine, and only then print the complaint. The complaint is printed only when the loop didn't stop.