Control Flow – Making Decisions and Repeating Actions with Conditionals and Loops
Your first programs ran in a straight line. But real programs need to make decisions ("if the user's password is correct, log them in") and repeat actions ("print numbers 1 to 1000"). This is called control flow – the ability to change the order in which instructions execute.
1. Conditionals – If This, Then That
# Basic if statement
temperature = 30
if temperature > 25:
print("It is hot outside.")
# if-else statement
password = input("Enter password: ")
if password == "secret123":
print("Access granted.")
else:
print("Access denied.")
# if-elif-else – multiple paths
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("Your grade is", grade)
Conditions use comparison operators: == (equal), != (not equal), >, <, >=, <=. Logical operators combine conditions: and, or, not.
Indentation matters in Python: Indentation (4 spaces) defines which code belongs to the if block. Other languages use braces {}.
2. The for Loop – Iterating Over a Range or Collection
# Print numbers 1 to 5
for i in range(1, 6):
print(i)
# Iterate over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print("I like", fruit)
# Sum of first 100 numbers
total = 0
for num in range(1, 101):
total = total + num
print("Sum of 1 to 100:", total) # 5050
3. The while Loop – Repeat Until a Condition Changes
# Countdown from 5 to 1
count = 5
while count > 0:
print(count)
count = count - 1
print("Blast off!")
# Keep asking until user enters a valid number
user_input = input("Enter a positive number: ")
while int(user_input) <= 0:
print("That is not positive.")
user_input = input("Try again: ")
Risk: If the condition never becomes false, the loop runs forever (infinite loop). Always ensure the loop variable changes toward the stopping condition.
4. Controlling Loops – break and continue
# break – exit loop immediately
for i in range(1, 10):
if i == 5:
break
print(i) # prints 1 2 3 4 only
# continue – skip to next iteration
for i in range(1, 6):
if i == 3:
continue
print(i) # prints 1 2 4 5 (skips 3)
5. Real-World Example – Login System with Retries
max_attempts = 3
attempt = 0
logged_in = False
while attempt < max_attempts and not logged_in:
password = input("Enter password: ")
if password == "secret":
logged_in = True
print("Welcome!")
else:
attempt = attempt + 1
print(f"Wrong password. Attempts left: {max_attempts - attempt}")
if not logged_in:
print("Account locked.")
6. Common Mistakes
|
Mistake |
Why it fails |
Fix |
|
Using = instead of == in if |
Assignment instead of comparison. |
Use == for equality checks. |
|
Forgetting colon after if/for/while (Python) |
Syntax error. |
Add : at end of the line. |
|
Infinite loop (condition never false) |
Program hangs. |
Ensure loop variable changes. |
|
Off-by-one errors in range |
range(1, 5) gives 1,2,3,4 (not 5). |
Remember range stops before the end value. |
Summary
|
Term |
Definition |
|
Conditional |
Code that executes only if a condition is true (if, else, elif). |
|
for loop |
Repeats a block a known number of times (over a sequence). |
|
while loop |
Repeats a block as long as a condition remains true. |
|
break |
Exits the current loop immediately. |
|
continue |
Skips the rest of the current iteration and goes to the next. |
|
Infinite loop |
A loop whose termination condition is never met. |
Review Questions
- Write an if-elif-else statement that prints "Child" for age < 13, "Teenager" for age 13–19, and "Adult" for age 20+.
- What will the following loop print? for i in range(3, 10, 2): print(i)
- Explain the difference between break and continue using an example.