Chapter 3: Control Flow
So far, our programs have been "linear," meaning they execute from the first line to the last line in order. However, real-world software needs to make decisions. For example, a program might need to check if a user is logged in before showing private content. This is where Control Flow comes in.
1. Conditional Statements (If, Elif, Else)
Conditionals allow your code to execute different blocks depending on whether a condition is True or False. We use the if keyword to define the condition. If that condition isn't met, we can use elif (else if) to check a secondary condition, or else as a final catch-all.
score = 85
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
else:
print("Grade: C or lower")
2. Indentation Matters
In many languages, curly braces {} define blocks of code. Python is unique because it uses indentation. Everything you want to run inside an if block must be indented (usually by 4 spaces). If your indentation is inconsistent, Python will trigger an IndentationError.
3. Loops: Repeating Tasks
What if you want to print "Hello" 100 times? You wouldn't write the line 100 times. We use loops instead.
The For Loop
The for loop is used to iterate over a sequence (like a range of numbers or a list).
for i in range(5):
print("Iteration number:", i)
The While Loop
The while loop keeps running as long as a specified condition remains True. Be careful: if your condition never becomes False, you will create an "infinite loop" that crashes your program!
count = 0
while count < 3:
print("Still running...")
count += 1
Common Beginner Mistakes
- Comparison vs. Assignment: Remember that
==is for checking equality, while=is for assigning a value. Using one when you need the other is a very common bug. - Forgetting the Colon: Every
if,else,for, andwhilestatement must end with a colon:. - Infinite Loops: Always ensure the condition in a
whileloop will eventually be met (e.g., ensure your counter actually increases).
Try It Yourself
- Write a program that asks for a number (using
input()) and prints whether it is "Positive", "Negative", or "Zero". - Use a
forloop to print all even numbers between 1 and 20.
Using elif for Multiple Conditions
When you have more than two possible outcomes, chaining elif (short for "else if") statements keeps your code clean and readable.
score = 82
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
else:
print("Grade: F")
Nesting Conditionals
You can place an if statement inside another if statement to check more specific conditions. This is called nesting, and it's useful when a decision depends on more than one factor.
age = 20
has_id = True
if age >= 18:
if has_id:
print("Entry allowed")
else:
print("ID required")
else:
print("Too young to enter")
Be careful not to nest too deeply — if you find yourself with more than 3 levels of indentation, it's usually a sign your logic can be simplified.
CodeMaster Academy