While Loops
Count down to lift-off with while.
1countdown = 3
2while countdown > 0:
3 print(countdown)
4 countdown = countdown - 1
5print("Lift off!")
$ python3 main.py
3
2
1
Lift off!
Every line, explained
countdown = 3- This creates a variable: a named box that stores a value. In Python you just write name = value: the = stores the value on the right into the name on the left. No special type word, no semicolon; Python keeps it simple.
while countdown > 0:- A while loop repeats its indented body for as long as the condition is True. The condition is checked again before every trip around the loop. Here it keeps going while countdown is greater than 0.
print(countdown)- print(...) shows whatever is inside its round brackets in the terminal, then moves to a new line. It is written all in lowercase, and it needs both brackets. Prints 3, then 2, then 1.
countdown = countdown - 1- Takes 1 off countdown each trip. Without this line countdown would stay 3 forever and the loop would never end!
print("Lift off!")- print(...) shows whatever is inside its round brackets in the terminal, then moves to a new line. It is written all in lowercase, and it needs both brackets. Not indented, so it is outside the loop: it runs once, after the loop has finished.