06 - Control Flow
Control flow decides which statements run and how often they run.
A simple picture
Imagine walking through a game maze:
- a condition chooses one path;
- a
forloop visits each checkpoint; - a
whileloop keeps moving while a rule remains true; breakis an emergency exit.
start -> question? -> chosen path -> repeat if needed -> finish
Conditions
A condition is an expression whose answer is True or False. A branch is one possible path through the program.
score = 72
if score >= 90:
grade = "A"
elif score >= 60:
grade = "B"
else:
grade = "C"
print(grade)
Python tests conditions from top to bottom and runs the first matching branch. The else branch runs when no condition matches.
Notice the colon : and four beginning spaces. The spaces show which lines belong to each branch.
Nested conditions
age = 25
has_ticket = True
if age >= 18:
if has_ticket:
print("Enter")
else:
print("Buy a ticket")
else:
print("Not eligible")
Before nesting many levels, consider combining clear conditions with and. Functions provide another organisation tool in Chapter 10.
What is an iterable?
An iterable is a value that contains, or can produce, items one at a time. In simple words, Python can “go through” it.
Start with two iterables you already recognise:
- a string produces one character at a time;
range()produces one number at a time.
A list is a group written inside square brackets, such as [10, 20, 30]. Lists receive a complete lesson in Chapter 08. The table below is a map of iterable types you will gradually learn; you do not need to master them here.
Common iterables that you will use are:
| Iterable | Example items produced |
|---|---|
| List | [10, 20, 30] produces 10, then 20, then 30 |
| Tuple | ("red", "blue") produces "red", then "blue" |
| String | "cat" produces "c", then "a", then "t" |
| Set | {"Python", "Java"} produces each value; order is not guaranteed |
| Dictionary | {"name": "Ravi", "age": 20} produces its keys by default |
range() |
range(1, 4) produces 1, then 2, then 3 |
Beginner examples:
for letter in "cat":
print(letter)
for number in range(1, 4):
print(number)
An integer, float, or boolean is not iterable because it is one value, not a group of values:
# for number in 10: # TypeError: an integer is not iterable
# print(number)
You do not need to memorize the technical definition. When you see for, ask: “Can Python visit the values inside this object one by one?”
for loops
Use for to process each item in an iterable. The name after for receives one item at a time. This name is called the loop variable:
for number in range(1, 4):
print(number)
The loop runs three times:
numberbecomes1.numberbecomes2.numberbecomes3.
The loop variable is not required to be called item; choose a name that describes each value.
for letter in "Python":
print(letter)
Preview: looping through dictionaries from Chapter 09
Looping through a dictionary
By default, a dictionary loop visits keys:
student = {"name": "Ravi", "marks": 86}
for key in student:
print(key)
Use .values() for values and .items() for both keys and values:
for value in student.values():
print(value)
for key, value in student.items():
print(f"{key}: {value}")
range()
range(start, stop, step) produces numbers up to but not including stop:
range(5) # 0, 1, 2, 3, 4
range(2, 6) # 2, 3, 4, 5
range(10, 4, -2) # 10, 8, 6
for number in range(1, 6):
print(number)
Accumulation
Use a variable to remember work from earlier iterations:
total = 0
for number in range(1, 6):
total += number
print(total) # 15
while loops
Use while when the number of repetitions depends on a condition:
attempts = 0
while attempts < 3:
print("Attempt", attempts + 1)
attempts += 1
Always ensure something inside the loop can eventually make the condition false. Otherwise the loop never ends.
Important fact: before running a
whileloop, point to the line that will eventually make its condition false. If no such line exists, the loop may run forever.
break, continue, and pass
for number in range(1, 11):
if number == 5:
break # stop the loop completely
print(number)
for number in range(1, 6):
if number % 2 == 0:
continue # skip even numbers
print(number)
pass does nothing and is useful temporarily while designing a block:
score = 80
if score >= 50:
pass
The program above is valid, but pass produces no output. Replace it when the branch is ready.
else with loops
Python also allows else after a for or while loop. The else block runs when the loop finishes normally. It does not run when break stops the loop.
for number in range(2, 6):
print(number)
else:
print("The loop finished normally")
This is useful for searching:
numbers = [3, 7, 11]
target = 7
for number in numbers:
if number == target:
print("Found")
break
else:
print("Not found")
If target is not found, the loop reaches its end and the else block runs. If it is found, break runs and the else block is skipped.
Real-world example: menu loop
while True:
choice = input("Choose add, view, or exit: ").strip().lower()
if choice == "add":
print("Adding item")
elif choice == "view":
print("Showing items")
elif choice == "exit":
break
else:
print("Unknown choice")
Common mistakes
- Forgetting the colon after
if,for, orwhile. - Using
range(1, 5)expecting it to include 5. - Forgetting to update a
whileloop’s control variable. - Putting
breakoutside the intended loop. - Using
continuewithout understanding which code it skips.
Bug Hunter
Bug 1 — missing colon
age = 12
if age >= 10
print("Welcome")
Bug 2 — endless loop
count = 1
while count <= 3:
print(count)
Bug 3 — wrong range ending
for number in range(1, 5):
print(number)
The programmer expects 1 through 5, but range() stops before its stop value.
Show Bug Hunter fixes
# Bug 1
if age >= 10:
print("Welcome")
# Bug 2
count = 1
while count <= 3:
print(count)
count += 1
# Bug 3
for number in range(1, 6):
print(number)
Optional deeper look: how does a for loop get values?
Python asks the iterable for an iterator, an object that supplies one item at a time. The loop repeatedly asks that iterator for its next value. A special internal signal named StopIteration tells the loop that no items remain. Intermediate Python studies this protocol directly.
Practice
Try these problems on this page. Before coding, write the decision or repetition in plain English.
Problems
- Check whether a number is positive, negative, or zero.
- Find the larger of two numbers without
max(). - Find the largest of three numbers.
- Print numbers from 1 to 20.
- Print all even numbers in a range.
- Calculate the sum from 1 to
n. - Check whether a year is a leap year. A year is a leap year when it is divisible by 400, or when it is divisible by 4 but not by 100.
- Build a menu-driven calculator loop.
- Print a multiplication table for a chosen number.
- Check whether a number is prime.
Show hints
- Compare the number with zero using
ifandelif. - Keep the larger value in a variable.
- Compare each value with the current largest value.
- Use
range(1, 21). - A number is even when its remainder after division by 2 is zero.
- Start
totalat zero and add each number. - Translate each part of the written leap-year rule into remainder comparisons, then join them with
andandor. - Put the menu inside a loop and provide an exit choice.
- Multiply the chosen number by values from 1 to 10.
- Test divisors from 2 up to the number, then improve later.
Show solution ideas
- Use
if number > 0,elif number < 0, otherwise zero. - Start with
largest = a; use anifblock to replace it withbwhenbis greater. - Start with
largest = a, then comparebandc. for number in range(1, 21): print(number).- Add
if number % 2 == 0inside the loop. - Add every value in
range(1, n + 1). year % 400 == 0 or (year % 4 == 0 and year % 100 != 0).- Continue until the user chooses
exit. - Use
for multiplier in range(1, 11). - If any number from 2 through
n - 1divides evenly, it is not prime.
Homework
Build a menu-driven quiz with five questions, a score counter, and a final result. Include an option to exit before completing all questions.
Checkpoint
Write a countdown from ten to five, explain why a while loop terminates, and find the largest of three values without using max().