O
Octo
O
Octo
CoursesPricingDashboardPrivacyTerms

© 2026 Octo

Python Fundamentals
1Why Python2Variables & Data Types3Control Flow4Functions5Data Structures6Working with Files & Data7Libraries & Packages8Your First Python Project
Module 3

Control Flow

If/else, for loops, while loops, and logical operators — the decision-making logic that turns a list of instructions into a smart program.

The thermostat that thinks for itself

You have a thermostat in your home. It does not just display the temperature — it makes decisions. If the room drops below 68 degrees, it turns on the heater. If it rises above 75, it turns on the air conditioning. Otherwise, it does nothing.

That thermostat is running control flow. It checks a condition, and depending on whether that condition is true or false, it takes a different action. Every smart system in the world — from Netflix recommendations to self-driving cars to the spam filter in your email — runs on this same idea: check a condition, make a decision, repeat.

Without control flow, a program is just a list of instructions that runs top to bottom, every time, the same way. With control flow, a program can think.

temperature = 65

if temperature < 68:
    print("Turning on the heater")
elif temperature > 75:
    print("Turning on the AC")
else:
    print("Temperature is comfortable")

That is a thermostat in five lines of Python.

3control flow tools: if, for, while

90%of program logic is control flow

4 spacesindentation required by Python

If / elif / else — making decisions

The if statement is the most fundamental control structure in all of programming. It works exactly like a decision in real life.

Think of it as a bouncer at a club door:

age = 21

if age >= 21:
    print("Welcome in!")          # This runs
elif age >= 18:
    print("No drinks for you")
else:
    print("Come back in a few years")

The anatomy:

PartWhat it doesRequired?
if condition:Checks the first conditionYes — always required
elif condition:Checks if the first was false, then checks this oneOptional — use 0 or more
else:Runs if ALL conditions above were falseOptional — use 0 or 1
Indented blockThe code that runs when the condition is trueYes — 4 spaces per level
⚠️Indentation is not optional in Python
In most languages, indentation is cosmetic — it makes code look nice but does not affect how it runs. In Python, indentation IS the syntax. It tells Python which lines belong inside the `if` block. Use exactly 4 spaces (VS Code does this automatically when you press Tab). Mixing tabs and spaces will crash your program with an `IndentationError`.

Comparison operators

These are the tools you use inside conditions:

x = 10
print(x == 10)   # True  (equal to)
print(x != 5)    # True  (not equal to)
print(x > 5)     # True  (greater than)
print(x < 20)    # True  (less than)
print(x >= 10)   # True  (greater than or equal)
print(x <= 9)    # False (less than or equal)

Logical operators — combining conditions

What if you need to check multiple things at once? Use and, or, and not:

age = 25
has_id = True

if age >= 21 and has_id:
    print("Welcome in!")

temperature = 72
if temperature < 60 or temperature > 85:
    print("Extreme weather alert!")

is_raining = False
if not is_raining:
    print("No umbrella needed")

✗ Without AI

  • ✗True and True = True
  • ✗True and False = False
  • ✗False and True = False
  • ✗False and False = False

✓ With AI

  • ✓True or True = True
  • ✓True or False = True
  • ✓False or True = True
  • ✓False or False = False

There Are No Dumb Questions

"What is the difference between = and ==?"

= is assignment: "put this value in this box." == is comparison: "are these two things equal?" Writing if age = 21: is a common beginner mistake and Python will give you a SyntaxError. Always use == inside conditions.

"Can I write an if statement on one line?"

Technically yes: print("adult") if age >= 18 else print("minor"). But do not do this for anything beyond trivial checks. Readable code beats clever code. Use the full multi-line format until you are very comfortable with Python.

⚡

Grade Calculator

25 XP
Write a program that converts a numerical score to a letter grade: - 90-100: A - 80-89: B - 70-79: C - 60-69: D - Below 60: F ```python score = int(input("Enter your score: ")) # Write your if/elif/else chain here ``` Test with scores: 95, 85, 72, 63, 45. Does each one give the correct grade? _Hint: Start from the highest condition and work down. Check `score >= 90` first, then `score >= 80`, etc. The order matters because Python stops at the first true condition._

For loops — repeating with a plan

A for loop repeats a block of code once for each item in a sequence. Think of it as going through a checklist: for each item on the list, do this thing.

# 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

range() generates a sequence of numbers. It is how you say "do this N times":

# Print numbers 0 through 4
for i in range(5):
    print(i)
# Output: 0, 1, 2, 3, 4

# Print numbers 1 through 5
for i in range(1, 6):
    print(i)
# Output: 1, 2, 3, 4, 5

# Count by twos
for i in range(0, 10, 2):
    print(i)
# Output: 0, 2, 4, 6, 8
🔑range() stops BEFORE the end number
`range(5)` gives you 0, 1, 2, 3, 4 — five numbers, but it stops before 5. `range(1, 10)` gives you 1 through 9, not 1 through 10. This "up to but not including" pattern is consistent throughout Python (slicing works the same way). It trips up every beginner, but once you internalize it, it becomes natural.

Real-world for loop examples

# Calculate a total
prices = [9.99, 24.50, 3.75, 15.00]
total = 0
for price in prices:
    total = total + price
print(f"Total: ${total:.2f}")    # Total: $53.24

# Find the longest word
words = ["python", "programming", "is", "fun"]
longest = ""
for word in words:
    if len(word) > len(longest):
        longest = word
print(f"Longest word: {longest}")  # Longest word: programming

There Are No Dumb Questions

"What does the variable name in for x in list matter?"

You can use any name: for item in list, for banana in list, for x in list. The name is just a temporary label for the current item. Use descriptive names: for student in students is much clearer than for s in students. The name i is conventional for number indices.

"Can I change the list while looping through it?"

Do NOT modify a list while you are iterating over it — this creates unpredictable behavior. If you need to filter items, create a new list instead: new_list = [x for x in old_list if x > 10]. We will cover this pattern (list comprehensions) in Module 5.

While loops — repeating until a condition changes

A for loop knows in advance how many times it will run. A while loop keeps running until a condition becomes false. Think of it as "keep doing this until I say stop."

# Countdown
count = 5
while count > 0:
    print(count)
    count = count - 1
print("Blast off!")
# Output: 5, 4, 3, 2, 1, Blast off!

The classic use case: getting valid input from a user.

password = ""
while password != "secret123":
    password = input("Enter the password: ")
print("Access granted!")
⚠️Infinite loops will freeze your program
If the condition never becomes false, the loop runs forever. This is called an infinite loop:
# DO NOT RUN THIS
while True:
    print("This never stops")

Always make sure something inside the loop changes the condition. If your program freezes, press Ctrl+C in the terminal to force-quit it.

Break and continue — loop control

# break — exit the loop immediately
for number in range(100):
    if number == 5:
        break
    print(number)
# Output: 0, 1, 2, 3, 4

# continue — skip this iteration, go to next
for number in range(6):
    if number == 3:
        continue
    print(number)
# Output: 0, 1, 2, 4, 5

Start Loop
Condition True?
Run Loop Body
Update Variable
Exit Loop
Press enter or space to select a node. You can then use the arrow keys to move the node around. Press delete to remove it and escape to cancel.
Press enter or space to select an edge. You can then press delete to remove it or escape to cancel.

⚡

FizzBuzz — The Classic

25 XP
Write a program that prints numbers 1 to 30, but: - For multiples of 3, print "Fizz" instead of the number - For multiples of 5, print "Buzz" instead of the number - For multiples of both 3 AND 5, print "FizzBuzz" Expected first 15 lines: ``` 1, 2, Fizz, 4, Buzz, Fizz, 7, 8, Fizz, Buzz, 11, Fizz, 13, 14, FizzBuzz ``` _Hint: Use `%` (modulo) to check divisibility. `number % 3 == 0` means "number is divisible by 3." Check the combined condition (both 3 AND 5) FIRST — order of if/elif matters._

Nested loops and patterns

You can put loops inside loops. Think of a clock: the minute hand completes 60 loops for every single loop of the hour hand.

# Multiplication table (3x3)
for row in range(1, 4):
    for col in range(1, 4):
        print(f"{row} x {col} = {row * col}", end="   ")
    print()  # New line after each row

Output:

1 x 1 = 1   1 x 2 = 2   1 x 3 = 3
2 x 1 = 2   2 x 2 = 4   2 x 3 = 6
3 x 1 = 3   3 x 2 = 6   3 x 3 = 9

Putting it all together — a guessing game

Here is a small program that uses everything from this module:

import random

secret = random.randint(1, 20)
attempts = 0

print("I'm thinking of a number between 1 and 20.")

while True:
    guess = int(input("Your guess: "))
    attempts += 1

    if guess < secret:
        print("Too low!")
    elif guess > secret:
        print("Too high!")
    else:
        print(f"You got it in {attempts} attempts!")
        break

This uses: variables, type conversion, a while loop, if/elif/else, break, f-strings, and a library import. You already know every piece of this program.

⚡

Build the Guessing Game

50 XP
Type in the guessing game code above and run it. Then extend it with these features: 1. Limit the player to 5 guesses. After 5 wrong guesses, reveal the answer. 2. After the game ends, ask "Play again? (y/n)" and restart if they say yes. _Hint: For the guess limit, add a condition: `if attempts >= 5`. For replay, wrap the whole game in another `while True` loop that breaks when the user says "n"._

Key takeaways

  • if/elif/else lets your program make decisions — check conditions and take different paths
  • for loops repeat code for each item in a sequence — "do this for every item"
  • while loops repeat code until a condition changes — "keep doing this until..."
  • range(n) generates numbers 0 through n-1 — remember, it stops BEFORE n
  • break exits a loop immediately; continue skips to the next iteration
  • Indentation is mandatory in Python — 4 spaces per level, mixing tabs and spaces will crash
  • = assigns, == compares — the most common beginner bug in all of programming
  • Avoid infinite loops — make sure the while condition will eventually become false

?

Knowledge Check

1.What will this code print? ```python x = 15 if x > 20: print('A') elif x > 10: print('B') elif x > 5: print('C') else: print('D') ```

2.What numbers does `range(2, 8)` generate?

3.What is the output of this code? ```python for i in range(5): if i == 3: break print(i) ```

4.Which of the following will cause an infinite loop?

Previous

Variables & Data Types

Next

Functions