Imagine you’re deciding what to wear based on the weather. If it’s raining, you take an umbrella; if it’s sunny, you wear sunglasses. This is decision-making, and Python does the same using if-else statements.
Conditional statements allow programs to make choices. Based on certain conditions, the program can run different blocks of code.
💡 Analogy: Conditional statements are like a traffic light—when the light is green, cars go; when it's red, they stop. Computers need a way to make decisions just like we do in real life.
By the end of this lesson, you will be able to:
Use if, elif, and else statements in Python.
Write programs that make decisions based on user input.
Use logical operators to combine multiple conditions.
Conditional statements – Code that makes decisions based on conditions using if, elif, and else.
if statement – Checks a condition and runs a block of code if the condition is True.
elif statement – Short for "else if," used when multiple conditions need to be checked in sequence.
else statement – Runs when all previous conditions are False, providing a default action.
Indentation – The spaces at the beginning of a line that structure Python code, required for if statements.
Example
age = int(input("Enter your age: "))
if age >= 18:
print("You are an adult!")
elif age >= 13:
print("You are a teenager!")
else:
print("You are a child!")
Forgetting indentation: Python relies on indentation to define code blocks. if statements must be indented properly.
Using = instead of ==: if x = 10: ❌ (assignment error) vs. if x == 10: ✅ (comparison).
🔗 Practice on W3Schools: If Statements Tutorial – Learn how to write conditional statements in Python.
🔗 Try It Online: Run Your Code Here – Test your Python code instantly.
1️⃣ Basic Challenge:
Write a program that asks for a user's age and prints whether they are an adult or a minor.
2️⃣ Extended Challenge:
Modify your program to check if the user is a teenager (13-19 years old).
3️⃣ Advanced Challenge:
Write a program that asks the user for a test score and prints their grade based on this scale: A (90+), B (80-89), C (70-79), D (60-69), F (below 60).
Write the example from this lesson, ensuring you include:
✅ An if statement checking a condition
✅ An elif statement handling another case
✅ An else statement providing a default outcome
Read the example code before starting!