PyComplete Python Course
Beginner 55 min

Module 04 — Control Flow & Loops

Teaching your program to make decisions and repeat work — if/else, while, and for.

Prerequisite: Module 03 — Strings & User Input

After this lesson, you will be able to

  • Branch program logic with if / elif / else and the and/or/not operators
  • Repeat code with while loops, including a safe exit condition
  • Iterate with for loops and range(), including a step argument
  • Control loop flow precisely with break and continue

Concept & Syntax

Control flow is what turns a list of instructions into a program that can actually make decisions. Two tools do almost all of the work: if statements (decide whether to run some code) and loops (decide how many times to run some code).

A for loop is used when you know what you're iterating over — a range of numbers, a string, a list. A while loop is used when you want to repeat "until some condition changes," which might happen an unpredictable number of times — like re-prompting a user until they type valid input.

Syntax
if condition:
    ...
elif other_condition:
    ...
else:
    ...
 
while condition:
    ...
 
for item in range(5):
    ...

Examples

if / elif / else Very Easy

if / elif / else
age = 20
if age < 13:
    print("Child")
elif age < 20:
    print("Teenager")
else:
    print("Adult")
OutputAdult

Python checks each condition top to bottom and runs the first block whose condition is True, then skips the rest.

Combining conditions Easy

Combining conditions
age = 25
has_id = True
if age >= 18 and has_id:
    print("Entry allowed")
else:
    print("Entry denied")
OutputEntry allowed

and requires both sides to be True; or needs only one; not flips a boolean.

while loop with a running total Intermediate

while loop with a running total
total = 0
n = 1
while n <= 5:
    total = total + n
    n = n + 1
print(total)
Output15

The loop keeps running as long as n <= 5 stays True. Each pass adds n to total, then increases n — this is how you sum 1+2+3+4+5.

for loop over a string Easy

for loop over a string
for letter in "Py!":
    print(letter)
OutputP y !

A for loop can iterate directly over any sequence — including a string, character by character.

break and continue Real World

break and continue
for number in range(10):
    if number == 7:
        break
    if number % 2 != 0:
        continue
    print(number)
Output0 2 4 6

continue skips straight to the next iteration (skipping odd numbers here); break exits the loop entirely the moment number hits 7.

Visual Explanation

Check conditionTrue → run loop bodyUpdate / advanceRe-check conditionFalse → exit loop
Every loop — while or for — follows this same check → run → repeat shape.
🔍 What happens internally? (advanced)

Under the hood, Python compiles your source into bytecode and runs it on a virtual machine (the CPython interpreter). Variables are names in a namespace dictionary pointing at objects in memory — which is exactly what the memory panel in the tracer above is showing you.

Watch a for loop iterate

Use the controls below to run this example one line at a time and watch the interpreter's memory update live.

Code

Code
for i in range(5):
    print(i)

Interpreter state

Console output

Common Mistakes

✗ Common mistake 1

Forgetting to change the variable a while loop depends on creates an infinite loop that never stops.

✗ Avoid this
This raises the program hangs forever (must be force-stopped)
n = 1
while n <= 5:
    print(n)
    # forgot n = n + 1
✓ Better approach
Fixed
n = 1
while n <= 5:
    print(n)
    n = n + 1
✗ Common mistake 2

Using = (assignment) instead of == (comparison) inside an if is a very common typo.

✗ Avoid this
This raises SyntaxError: invalid syntax
age = 18
if age = 18:
    print("Just became an adult")
✓ Better approach
Fixed
age = 18
if age == 18:
    print("Just became an adult")
✓ Best practices
  • Use for when you know the number of iterations or are iterating over a collection.
  • Use while only when the stopping condition can't be known in advance.
  • Keep loop bodies short — extract a function if the logic inside grows past a few lines (the DRY principle: Don't Repeat Yourself).
  • Double-check every while loop has a way to eventually become False.

Exercise & Challenge

Exercise 1 — Debug this code

Given this code
for n in range(9):
    if n % 2 = 0:
        print(n)

This code should print all even numbers from 0 to 8, but it has a bug. What single character needs to change?

🏆 Challenge

Write a program using a while loop that keeps asking the user to 'Enter a number greater than 10' until they succeed, then prints 'Thanks!'.

  • Use a while loop with a condition that starts False
  • Convert input() to int() before comparing
  • Print 'Thanks!' once the loop ends
💡 Need a hint?

Initialize a variable to something that's guaranteed to fail the check the first time, e.g. number = 0.

🔍 Show a sample solution
Python
number = 0
while number <= 10:
    number = int(input("Enter a number greater than 10: "))
print("Thanks!")

Quiz

Answer every question, then submit to see your score and explanations.

1. What does the DRY principle stand for?

Do Repeat Yearly
Don't Repeat Yourself
Data Range Yield
Debug Regularly, Yes
DRY: Don't Repeat Yourself — avoid duplicating logic.

2. What's the difference between break and continue?

They're identical
break exits the loop; continue skips to the next iteration
break skips one line; continue exits the loop
Neither works inside for loops
break stops the loop completely; continue jumps to the next iteration.

3. What does range(5) produce?

1,2,3,4,5
0,1,2,3,4
0,1,2,3,4,5
5 only
range(5) produces 5 values starting at 0: 0,1,2,3,4.

4. Which operator checks equality (not assignment)?

=
==
!=
eq()
== compares two values for equality.

5. When should you prefer a for loop over a while loop?

When the number of iterations is unknown
When iterating over a known collection or range
Never — while is always better
Only inside functions
for loops shine when you're iterating over something with a known size.

Summary

  • if/elif/else branches your program based on conditions, checked top to bottom.
  • and, or, and not combine boolean conditions.
  • while repeats until a condition becomes False — make sure it eventually does.
  • for iterates over a known sequence; break exits early, continue skips ahead.

Related lessons

Saved privately in your browser — no account needed.