Lesson 3 of 34 · 0 of 3 exercises solved

Control Flow

Conditions and let your program make decisions and repeat work. In Python, (not curly braces) marks which lines belong to each block.

Python's if/elif/else statements work like you'd expect. The colon after the condition is required, and the body must be indented consistently (4 spaces is the standard). Python uses elif (not else if) for chained conditions.

age = 20

if age < 13:
    print("child")
elif age < 18:
    print("teenager")
elif age < 65:
    print("adult")
else:
    print("senior")

# Comparison operators
x = 10
print(x > 5)    # True
print(x == 10)  # True (== for equality, not =)
print(x != 3)   # True
print(x >= 10)  # True

# Logical operators
print(x > 5 and x < 20)   # True
print(x < 0 or x > 5)     # True
print(not True)             # False
Python (loads on first run)Ctrl+Enter runs

Python has two loop types: for (iterates over a sequence) and while (runs while a condition is true). The for loop is used far more often in idiomatic Python.

# For loop over a range
for i in range(5):
    print(i)   # 0, 1, 2, 3, 4

# range(start, stop, step)
for i in range(0, 10, 2):
    print(i)   # 0, 2, 4, 6, 8

# For loop over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

# While loop
count = 0
while count < 5:
    print(count)
    count += 1

# break and continue
for i in range(10):
    if i == 3:
        continue   # skip 3
    if i == 7:
        break      # stop at 7
    print(i)       # 0, 1, 2, 4, 5, 6
Python (loads on first run)Ctrl+Enter runs

Common question

Is indentation in Python just a style choice?

Control flow is the order in which statements run. Conditionals pick one path out of several; loops repeat a path. Python marks where each path starts and ends with indentation: the lines indented under a colon belong to it, and the first line back at the previous level ends it. Because Python reads structure from the same cue your eye does, code cannot look one way and behave another.

The practical rules: use four spaces, never mix tabs and spaces, and end each header (if, elif, else, for, while) with a colon. range stops before its end value. Use for when walking through a collection and while when repeating until something changes, and use to steer the loop from inside.

Source: The Python grammar defines a block as INDENT statements DEDENT. Indentation is a token, not whitespace.

Common mix-ups

Each of these sounds reasonable. Think about why it is wrong, then open the explanation.

  • In other languages indentation is just decoration, so it must be the same in Python.

  • A for loop over an empty does nothing, so Python must skip those loops to save time.

  • while True is a , because a condition that is always true can never end.

Practice

The classic. For each number from 1 to 20, print Fizz if it is divisible by 3, Buzz if divisible by 5, FizzBuzz if divisible by both, and the number itself otherwise — one item per line.

Exercise

FizzBuzz

2 checks
for n in range(1, 21):
    # your logic here
    print(n)
 
Python (loads on first run)Ctrl+Enter runs
Output
Press Run to try your code, then Check answer to grade it.

Using a while loop (not for), add up every even number from 1 to 100 inclusive and store the result in total. Print it at the end.

Exercise

Sum the evens with while

2 checks
total = 0
n = 1

# loop while n <= 100

print(total)
 
Python (loads on first run)Ctrl+Enter runs
Output
Press Run to try your code, then Check answer to grade it.

Convert each score in the list to a letter grade and print the letters one per line: 90 and above is A, 80–89 is B, 70–79 is C, 60–69 is D, anything lower is F.

Exercise

Letter grades

2 checks
scores = [95, 82, 71, 64, 50]

for score in scores:
    # decide the letter, then print it
    pass
 
Python (loads on first run)Ctrl+Enter runs
Output
Press Run to try your code, then Check answer to grade it.

Check yourself

Quick check

What does list(range(1, 5)) evaluate to?

Finished reading?3 exercises still open. You can come back to them later.

Tip: use the ← and → keys to move between lessons.