Repeating with while
A while loop repeats a block as long as its condition is true.
count = 3
while count > 0:
print(count)
count = count - 1
print("Liftoff!")
Here is exactly what happens: Python checks count > 0. True, so it runs the indented block, then jumps back up and checks again. When the condition finally comes out false, it skips the block and carries on with the line after the loop. The condition is only checked at the top of each round, not halfway through.
The block must change something that the condition depends on. Delete the line count = count - 1 and count stays 3 forever, so the condition never becomes false. That is an infinite loop, and your program will hang until you stop it. Everyone writes one eventually; consider it a rite of passage.
A shortcut you will see everywhere: count -= 1 means count = count - 1. Same for +=, *= and friends.
Sometimes you do not know in advance when to stop. Then you can write while True: (a loop that would run forever) and use break to jump out from inside:
while True:
guess = input()
if guess == "42":
break
while is the right tool when you are repeating "until something happens": until the user types the right password, until a number gets small enough, until the game is over. When you know how many times to repeat, or you are going through a collection of things, the for loop in the next lesson is usually cleaner.
Try it yourself
Edit it. Break it. Run it again.count = 3
while count > 0:
print(count)
count -= 1
print("Liftoff!")
# How many times can we double 1 before passing 1000?
n = 1
steps = 0
while n <= 1000:
n *= 2
steps += 1
print(f"{steps} doublings gives {n}")
Your turn
Type it yourself. That is the whole trick.1Count by threes
Use a while loop to print the numbers 3, 6, 9, 12 and 15, each on its own line.
n = 3
while n <= 15:
print(n)
n += 1
2Guess the password
Keep reading lines with input() until someone types open sesame. For every wrong guess print Nope. When the right guess arrives, print Welcome in and stop. With the given input, the output is two Nope lines then Welcome in.
The checker feeds this input to your program.
guess = input()
print("Welcome in")