Skip to content

Control Flow: If, Else, Loops

💡
Before you start

You need Python installed, and to know how to run a .py file. If python3 --version in a terminal prints a version number, you are ready. If it does not — or if you have never opened a terminal — do Getting Started with Python first; it installs Python and runs your first program, and takes about fifteen minutes. Nothing else is needed: no account, no payment, no extra software.

If Statements

An if statement lets your program make decisions. It runs a block of code only when a condition is true.

age = 18

if age >= 18:
    print("You are an adult.")
    print("You can vote!")
💡
Indentation matters!

Python uses indentation (4 spaces) to define code blocks. The indented lines after the if statement only run when the condition is true. This is different from most other languages that use braces {}.

If-Else

Add an else block to handle what happens when the condition is false:

temperature = 35

if temperature > 30:
    print("It's hot outside!")
else:
    print("The weather is nice.")

If-Elif-Else

Use elif (short for "else if") to check multiple conditions:

score = 85

if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
elif score >= 60:
    grade = "D"
else:
    grade = "F"

print(f"Your grade: {grade}")    # Your grade: B

Python checks each condition from top to bottom and runs the first one that's true. If none match, the else block runs.

Comparison and Logical Operators

Use these operators in your conditions:

# Comparison operators
x == y     # Equal to
x != y     # Not equal to
x > y      # Greater than
x < y      # Less than
x >= y     # Greater than or equal
x <= y     # Less than or equal

# Logical operators (combine conditions)
x > 0 and x < 100     # Both must be true
x < 0 or x > 100      # At least one must be true
not (x > 0)            # Inverts the result

Example with logical operators:

age = 25
has_license = True

if age >= 18 and has_license:
    print("You can drive!")
else:
    print("You cannot drive.")

For Loops

A for loop repeats code for each item in a sequence:

# Loop through a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(f"I like {fruit}")

# Output:
# I like apple
# I like banana
# I like cherry

The range() Function

Use range() to loop a specific number of times:

# Count from 0 to 4
for i in range(5):
    print(i)        # 0, 1, 2, 3, 4

# Count from 1 to 5
for i in range(1, 6):
    print(i)        # 1, 2, 3, 4, 5

# Count by 2s
for i in range(0, 10, 2):
    print(i)        # 0, 2, 4, 6, 8

Looping Through Strings

for char in "Python":
    print(char)     # P, y, t, h, o, n

While Loops

A while loop repeats code as long as a condition remains true:

count = 0
while count < 5:
    print(f"Count: {count}")
    count += 1          # Don't forget to update!

# Output: Count: 0, Count: 1, ... Count: 4
⚠️
Infinite loops

If you forget to update the condition variable, the loop runs forever. Always make sure the condition will eventually become false. Press Ctrl + C to stop an infinite loop.

Practical While Loop Example

# Simple password checker
password = ""
while password != "secret123":
    password = input("Enter password: ")
    if password != "secret123":
        print("Wrong password, try again.")

print("Access granted!")

Break and Continue

break exits the loop immediately. continue skips to the next iteration:

# break example: stop at the first negative number
numbers = [10, 25, -3, 8, 15]
for num in numbers:
    if num < 0:
        print("Negative number found! Stopping.")
        break
    print(num)
# Output: 10, 25, Negative number found! Stopping.

# continue example: skip even numbers
for i in range(10):
    if i % 2 == 0:
        continue
    print(i)
# Output: 1, 3, 5, 7, 9

Nested Loops

You can put loops inside loops:

# Multiplication table
for i in range(1, 4):
    for j in range(1, 4):
        print(f"{i} x {j} = {i * j}")
    print("---")

# Output:
# 1 x 1 = 1
# 1 x 2 = 2
# 1 x 3 = 3
# ---
# 2 x 1 = 2
# ...

Now Do It Yourself: Five Steps

Control flow is how a program makes decisions and repeats work. You will build a small grade reporter that does both. Every output and every error below is exactly what Python printed.

1
Make a decision with if, elif and else

Go: open a terminal, run cd ~, and create a file called grades.py in your editor.

Do: type these six lines and run python3 grades.py. The four spaces before each print matter — they are not decoration.

score = 72
if score >= 90:
    print("A")
elif score >= 70:
    print("B")
else:
    print("C")

You should see: a single B. Python checks each test top to bottom and stops at the first true one — 72 is not >= 90, it is >= 70, so B wins and else is never reached.

If not: IndentationError: expected an indented block after 'if' statement on line 1 means the print is not indented. Python uses indentation the way other languages use braces — it is the syntax, not the style. And SyntaxError: expected ':' means you left the colon off the end of the if line.

2
Repeat an action over a list

Go: same file, replace everything in it.

Do: type these two lines and run it again.

for name in ["Alice", "Bob", "Carol"]:
    print("Hello,", name)

You should see: three lines — Hello, Alice, Hello, Bob, Hello, Carol. The loop body runs once per item, and name holds a different value each time round.

If not: if only one line prints, the print is not indented and therefore is not inside the loop — it runs once, after the loop finishes. That is the most common loop mistake there is, and Python will not warn you, because unindented code after a loop is perfectly legal.

3
Count with range, and build up a total

Go: same file, replace the contents again.

Do: type these four lines and run it.

total = 0
for n in range(1, 6):
    total = total + n
print(total)

You should see: 15 — that is 1+2+3+4+5. Note carefully that range(1, 6) stops before 6. The end is never included, which trips up everyone at first and is consistent everywhere in Python.

If not: if you get 21, you wrote range(1, 7). If you get 0, the total = total + n line is not indented, so it never ran inside the loop. If total is undefined, the first line is missing — a variable must exist before you can add to it.

4
Loop until something happens, then stop

Go: same file, replace the contents.

Do: type these six lines and run it.

tries = 0
while True:
    tries = tries + 1
    if tries == 3:
        print("stopped after", tries, "tries")
        break

You should see: stopped after 3 tries, once. while True means "loop forever", and break is the exit. Use this shape when you do not know in advance how many times to go round.

If not: if the terminal fills with output and will not stop, the break is missing or misindented and you have written an infinite loop. Press Ctrl + C to stop it — that is the universal "cancel this" in a terminal, and it is worth knowing before you need it.

5
Put the pieces together

Go: same file, one last time.

Do: type these seven lines and run it.

scores = [95, 72, 58, 88]
for score in scores:
    if score >= 90:
        print(score, "A")
    elif score >= 70:
        print(score, "B")
    else:
        print(score, "C")

You should see: four lines — 95 A, 72 B, 58 C, 88 B. A loop with a decision inside it is most of everyday programming.

If not: if every line prints C, your if tests are indented one level too far and are being read as part of the wrong block. Count the spaces: the if sits four spaces in, the print under it sits eight.

🎉
Check yourself before moving on

Without scrolling up: how many numbers does range(1, 6) produce, and what is the last one? Answer: five numbers, and the last is 5 — the end value is never included.

Now do it without the page: change step 5 so it also prints a running count of how many students got an A. You need one variable before the loop and one + 1 inside it — the same shape as step 3.

Summary

  • if/elif/else let your program make decisions based on conditions
  • for loops iterate over sequences (lists, strings, ranges)
  • while loops repeat while a condition is true
  • break exits a loop; continue skips to the next iteration
  • Indentation (4 spaces) defines code blocks in Python
  • Logical operators (and, or, not) combine conditions
🎉
Control flow mastered!

Your programs can now make decisions and repeat tasks. Next up: functions and modules — organizing your code into reusable building blocks.