Python Foundations · Day 3

Control Flow: Decisions and Loops

What you will cover

if/elif/else, truthy/falsy values, while and for loops, range(), break, continue, pass and nested loops.

How to use this day

Plan about 2 hours. Type every loop example and modify conditions to see how behaviour changes.

DAY 3 - Control Flow: Decisions and Loops

3.1 Conditional Statements - if, elif, else

So far, your programmes have executed every line from top to bottom without making any decisions. Conditional statements let your code choose different paths based on whether a condition is True or False.

temperature = 22

if temperature > 25:
    print("It's hot - stay hydrated.")
elif temperature > 15:
    print("It's pleasant - enjoy the day.")
else:
    print("It's cool - grab a jacket.")

Output:

It's pleasant - enjoy the day.

The rules

  • The condition after if or elif must evaluate to True or False.
  • The colon : at the end of each if/elif/else line is mandatory.
  • The code inside each block must be indented - Python uses 4 spaces as the standard. This is not just style; it is how Python understands which lines belong to which block.
  • elif is short for “else if” - you can have as many as you need.
  • else is optional and catches everything not matched above.

Nested conditions

You can place if statements inside other if statements:

age = 20
has_id = True

if age >= 18:
    if has_id:
        print("Entry permitted.")
    else:
        print("ID required.")
else:
    print("Entry denied - must be 18 or over.")

Use nesting sparingly. Deep nesting makes code hard to read. Often, logical operators (and, or) can replace a nested if:

if age >= 18 and has_id:
    print("Entry permitted.")

Truthy and falsy values

In Python, non-Boolean values can be evaluated as True or False in a condition:

ValueEvaluates as
0, 0.0False
"" (empty string)False
NoneFalse
Any non-zero numberTrue
Any non-empty stringTrue
name = ""
if name:
    print(f"Hello, {name}!")
else:
    print("No name provided.")
# Output: No name provided.

This pattern is used constantly in data cleaning to check for missing values.

3.2 while Loops

A while loop repeats a block of code as long as a condition remains True:

count = 0

while count < 5:
    print(f"Count is: {count}")
    count += 1

print("Loop finished.")

Output:

Count is: 0
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Loop finished.

Infinite loops - if your condition never becomes False, the loop runs forever and freezes your programme. Always ensure something inside the loop changes the condition. If you accidentally create one, press Ctrl + C to stop it.

A practical while example - input validation

age = int(input("Enter your age: "))

while age < 0 or age > 120:
    print("Invalid age. Please try again.")
    age = int(input("Enter your age: "))

print(f"Age accepted: {age}")

3.3 for Loops

A for loop iterates over a sequence, executing the block once for each item:

cities = ["London", "Paris", "Berlin", "Madrid"]

for city in cities:
    print(f"Visiting {city}")

Output:

Visiting London
Visiting Paris
Visiting Berlin
Visiting Madrid

You do not need to manage a counter - Python handles it for you.

Looping over a string

Strings are sequences of characters, so you can loop over them too:

for letter in "Python":
    print(letter)

3.4 The range() Function

range() generates a sequence of numbers without creating a list in memory. It is the standard way to loop a specific number of times:

# range(stop) - from 0 up to (but not including) stop
for i in range(5):
    print(i)   # 0, 1, 2, 3, 4

# range(start, stop) - from start up to (but not including) stop
for i in range(2, 8):
    print(i)   # 2, 3, 4, 5, 6, 7

# range(start, stop, step) - with a step
for i in range(0, 20, 5):
    print(i)   # 0, 5, 10, 15

# Counting backwards
for i in range(10, 0, -1):
    print(i)   # 10, 9, 8, ..., 1

3.5 break, continue and pass

break - exit the loop immediately

for number in range(10):
    if number == 5:
        print("Found 5, stopping.")
        break
    print(number)
# Output: 0, 1, 2, 3, 4, Found 5, stopping.

continue - skip the rest of this iteration and move to the next

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

pass - do nothing (placeholder)

pass is used when Python requires a code block but you have nothing to put there yet:

for i in range(5):
    pass   # TODO: implement this later

3.6 Nested Loops

Loops can be placed inside other loops. The inner loop completes fully for each iteration of the outer loop:

for row in range(1, 4):
    for col in range(1, 4):
        print(f"({row},{col})", end=" ")
    print()  # new line after each row

Output:

(1,1) (1,2) (1,3)
(2,1) (2,2) (2,3)
(3,1) (3,2) (3,3)

The end=" " argument in print() replaces the default newline with a space, keeping all items on the same row.

✏️ Day 3 Exercises

Exercise 3.1 - FizzBuzz

The classic. Write a programme that prints the numbers from 1 to 50. But:

  • For multiples of 3, print "Fizz" instead of the number.
  • For multiples of 5, print "Buzz" instead.
  • For multiples of both 3 and 5, print "FizzBuzz".

Expected output (first 16 lines):

1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
...

Hint: check for the combined condition (FizzBuzz) first. Use the modulo operator % to check divisibility: n % 3 == 0 means n is divisible by 3.

Exercise 3.2 - Grade Classifier

Ask the user for a numerical score (0–100). Print the corresponding grade and a message:

ScoreGradeMessage
90–100AExcellent
75–89BGood work
60–74CSatisfactory
40–59DNeeds improvement
0–39FPlease see your tutor

Also validate that the score is between 0 and 100 before proceeding. Use a while loop to keep asking until the score is valid, then use if/elif/else to classify.

Exercise 3.3 - Multiplication Table Generator

Ask the user for a number. Print its multiplication table from 1 to 12, neatly formatted, for example for 7:

Multiplication table for 7
7  x  1  =   7
7  x  2  =  14
7  x  3  =  21
...
7  x 12  =  84

Hint: use an f-string with width specifiers to align the numbers: f"{value:3d}" reserves 3 characters for an integer, right-aligned.

Exercise 3.4 - Challenge: Number Guessing Game

Write a programme that:

  1. Secretly stores a target number (for example 42 - no need for randomness yet).
  2. Asks the user to guess the number.
  3. Tells them if their guess is too high, too low or correct.
  4. Keeps asking until they guess correctly.
  5. Prints how many attempts it took.

Hint: use a while True: loop with a break when the correct answer is found. Use a counter variable to track attempts.

📌 Day 3 Summary

ConceptWhat you learned
if/elif/elseExecute different blocks based on conditions
Truthy / FalsyNon-Boolean values used in conditions
whileRepeat while a condition is True
forIterate over a sequence
range()Generate a sequence of numbers
breakExit a loop immediately
continueSkip to the next iteration
passPlaceholder - does nothing
Nested loopsLoops inside loops

Tomorrow you will learn about Python's most powerful built-in data structures - the tools you will use to store and manipulate datasets before you even touch pandas.