Skip to content

Decisions and loops: if, for, range and while

BeginnerLesson 7 of 148 min

Make Python choose with if, elif and else, repeat with for and range(), loop until something happens with while, and stop early with break.

if, elif, else

if runs a block of code only when its condition is true. The block is the indented lines after the colon:

battery = 15
if battery < 20:
    print("Low battery")
    print("Plug in soon")
print("This line always runs")

Python uses indentation, not brackets, to know which lines belong to the if. Four spaces is the habit; the editor adds them for you after a colon.

Add elif (else if) and else for more choices. Python checks them top to bottom and runs only the first that's true:

battery = 55
if battery < 20:
    print("low")
elif battery < 80:
    print("fine")
else:
    print("full")

Conditions use comparisons: == (equal: two signs, one sign assigns), !=, <, <=, >, >=, and combine with and, or and not.

for

for runs a block once for each item of a list, string, dict or anything else you can go through:

for city in ["Lagos", "Quito", "Osaka"]:
    print("Hello,", city)

range() makes numbers to loop over. Like a slice, it stops before its end:

for n in range(3):
    print(n)            # 0, 1, 2
for n in range(10, 0, -3):
    print(n)            # 10, 7, 4, 1: start, stop, step

while and break

while repeats as long as its condition stays true, for when you don't know how many times in advance. break leaves a loop straight away:

savings = 100
years = 0
while True:
    if savings >= 150:
        break
    savings = savings * 1.1
    years += 1
print(years, "years")   # 5 years

Careful:A while loop whose condition never becomes false runs for ever. If that happens here, press Stop.

More in the Python docs: control flow and range().

Your turn

temps are fridge readings. Loop over them and print each with a label: cold below 2, ok from 2 up to and including 5, and warm above 5 (like 3 ok). Then use a loop with break to find the position of the first warm reading, and store it in first_warm.

Next →