Conditional Statements in Programming
A Friendly Guide
Making your code smart enough to make decisions – like choosing what to wear based on the weather!
What are Conditional Statements?
Think of them as decision-making tools for your program
Like a Traffic Light Choosing a Path Program Logic
Red means stop, green means go Different doors lead to different Helps programs respond
– your code follows rules too! rooms – conditions choose which differently based on situations
code runs
The if Statement
Your First Decision Maker
Basic Syntax Real Example
if condition: # code runs if True age = 18if age >= 18: print("You can
print("Yes!") vote!") # Output: You can vote!
The code inside runs only if the condition is True
Simple check: is age 18 or more?
Adding else
When Things Don't Go as Planned
The else block catches everything that doesn't match the if condition
Syntax Structure Practical Code
if condition: # if True action_1()else: # temperature = 15if temperature > 25: print("Wear
if False action_2() shorts!")else: print("Bring a jacket!") #
Output: Bring a jacket!
Either one block runs or the other – never both!
The elif Ladder
Multiple Choices Made Easy
Check Second Condition
Check First Condition
elif score >= 75: grade = "B"
if score >= 90: grade = "A"
Default Action
Check Third Condition
else: grade = "F"
elif score >= 60: grade = "C"
Key point: Only the first True condition executes, then it stops checking!
Nested Conditions
Conditions Inside Conditions
age = 20has_license = Trueif age >= 18:
Visual Structure
print("Adult") if has_license: print("Can
drive!") else: print("Need license")else: Outer Check
print("Too young")
Is age ≥ 18?
Inner Check
Has license?
Each level adds another decision layer
The inner if only runs when outer if is True
Comparison Operators
The Building Blocks of Decision Making
== !=
Equal to Not equal to
5 == 5 # True5 == 3 # False 5 != 3 # True5 != 5 # False
>< >= <=
Greater/Less than Greater/Less or equal
5 > 3 # True3 < 5 # True 5 >= 5 # True3 <= 5 # True
These operators create True or False values for your conditions
Logical Operators
Combining Conditions Like a Pro
and Operator or Operator not Operator
Both conditions must be True At least one condition must be True Reverses the condition
age = 25income = 50000if day = "Saturday"if day is_raining = Falseif not
age > 18 and income > == "Saturday" or day == is_raining: print("Let's
30000: print("Loan "Sunday": print("It's go outside!") # False
approved!") # Both weekend!") # One becomes True ✓
checks pass ✓ check passes ✓
Flow Chart Magic
Visualising How Decisions Flow in Your Program
Deny entry
Block access
Allow entry
Grant access
Is age >= 18?
Check eligibility
Get user age
Prompt for age input
Common Mistakes and How to Avoid Them
Using = instead of ==
1
# Wrong