Python While Loops
A loop repeats a block of code. The while loop repeats its block as long as a condition is true. It checks the condition, runs the block, checks again, and so on. When the condition becomes false, the program continues after the loop. Use while when you do not know in advance how many times something must happen.
A simple counter
count = 1
while count <= 5:
print("Count:", count)
count += 1
print("Done!")Count: 1 Count: 2 Count: 3 Count: 4 Count: 5 Done!
The line count += 1 is essential. Without it count would stay 1 forever, the condition would never become false and the loop would never end. Such an endless loop keeps the program busy; press Ctrl+C or Stop to end it. In our editor a program that runs for a long time without waiting for input is also stopped automatically.
break and continue
break leaves the loop at once. continue skips the rest of the block and goes back to the condition:
n = 0
while n < 10:
n += 1
if n % 2 == 0:
continue # skip even numbers
if n > 7:
break # stop after 7
print(n, end=" ")
print()1 3 5 7
Asking until the input is valid
A common pattern is a loop that keeps asking until the user gives a good answer. while True repeats forever, and break leaves when the answer is acceptable:
while True:
answer = input("Enter a number from 1 to 10: ")
if answer.isdigit() and 1 <= int(answer) <= 10:
break
print("That is not a number from 1 to 10.")
print("You chose", answer)twelve 15 7
Enter a number from 1 to 10: That is not a number from 1 to 10. Enter a number from 1 to 10: That is not a number from 1 to 10. Enter a number from 1 to 10: You chose 7
while with else
A while loop can have an else block. It runs when the condition becomes false, but not when the loop is left with break. It is useful for searches: the else part says "the loop finished without finding anything".
Practice exercises
- Print the numbers from 10 down to 1, then "Lift off!".
- Ask for numbers until the user types 0, then print the total of all the numbers.
- Find the first power of 2 that is greater than 1000 with a
whileloop. - Write a guessing game: the secret number is 7, and the program asks until the user guesses it, saying "higher" or "lower" each time.