Conditional Statements: Making Smart Decisions
Welcome to the decision-making world of programming! Just like in real life, your programs need to make choices based on different situations.
What are Conditional Statements?
Conditional statements are like traffic lights for your code:
- Green light (if): Go ahead if condition is true
- Yellow light (elif): Alternative path if first condition fails
- Red light (else): Stop and do this if all else fails
The Basic if Statement
Real-Life Example: Coffee Shop Decision
hungry = True
has_money = True
if hungry:
print("Let's get some food!")
if has_money:
print("I can afford it!")
# Both conditions are checked independently
Code Example: Age Verification
age = 25
if age >= 18:
print("You are eligible to vote!")
print("You can also get a driver's license!")
print("Age check complete.") # This always runs
if-else Statement
Real-Life Example: Weather Decision
is_raining = True
if is_raining:
print("Take an umbrella!")
print("Wear rain boots!")
else:
print("Enjoy the sunshine!")
print("Wear sunglasses!")
print("Ready for the day!")
Code Example: Pass/Fail System
score = 75
passing_score = 60
if score >= passing_score:
print("Congratulations! You passed!")
print(f"Your score: {score}/{passing_score}")
else:
print("Sorry, you didn't pass.")
print(f"You needed {passing_score}, but got {score}")
print("Better luck next time!")
print("Exam evaluation complete.")
Multiple Conditions with elif
Real-Life Example: Movie Rating System
age = 16
if age >= 18:
print("You can watch R-rated movies!")
elif age >= 13:
print("You can watch PG-13 movies!")
elif age >= 10:
print("You can watch PG movies!")
else:
print("You can watch G-rated movies!")
print("Movie selection complete.")
Code Example: Grade Calculator
marks = 87
if marks >= 90:
grade = "A"
feedback = "Excellent work!"
elif marks >= 80:
grade = "B"
feedback = "Good job!"
elif marks >= 70:
grade = "C"
feedback = "Satisfactory"
elif marks >= 60:
grade = "D"
feedback = "Needs improvement"
else:
grade = "F"
feedback = "Try harder next time"
print(f"Your grade: {grade}")
print(f"Feedback: {feedback}")
Nested if Statements
Real-Life Example: Restaurant Decision
has_reservation = True
party_size = 6
is_vegetarian = False
if has_reservation:
print("Welcome! You have a reservation.")
if party_size <= 4:
print("Table for 4 is ready.")
if is_vegetarian:
print("Would you like the vegetarian special?")
else:
print("Our chef recommends the steak tonight.")
else:
print("Large party - please wait 15 minutes.")
else:
print("Sorry, we require reservations for parties over 2.")
Code Example: Login System
username = "admin"
password = "secret123"
is_admin = True
if username == "admin":
if password == "secret123":
print("Login successful!")
if is_admin:
print("Welcome, Administrator!")
print("You have full access.")
else:
print("Welcome, User!")
print("You have limited access.")
else:
print("Incorrect password!")
else:
print("Username not found!")
Comparison Operators
Basic Comparisons
x = 10
y = 20
# Equal to
if x == y:
print("x equals y")
# Not equal to
if x != y:
print("x is not equal to y")
# Greater than
if x > y:
print("x is greater than y")
# Less than
if x < y:
print("x is less than y")
# Greater than or equal to
if x >= y:
print("x is greater than or equal to y")
# Less than or equal to
if x <= y:
print("x is less than or equal to y")
String Comparisons
name = "Alice"
if name == "Alice":
print("Hello, Alice!")
if name != "Bob":
print("You're not Bob!")
# Case-sensitive comparison
if name.lower() == "alice":
print("Hello, alice (case-insensitive)!")
Logical Operators
and Operator (Both conditions must be true)
age = 25
has_license = True
if age >= 18 and has_license:
print("You can drive legally!")
else:
print("You cannot drive legally.")
# Multiple conditions
temperature = 75
is_sunny = True
has_sunscreen = True
if temperature > 70 and is_sunny and has_sunscreen:
print("Perfect day for the beach!")
else:
print("Maybe stay indoors today.")
or Operator (At least one condition must be true)
is_weekend = False
is_holiday = True
if is_weekend or is_holiday:
print("You can sleep in!")
else:
print("Time to wake up for work!")
# Multiple conditions
has_cash = False
has_card = True
accepts_crypto = False
if has_cash or has_card or accepts_crypto:
print("You can make the purchase!")
else:
print("Payment method not accepted.")
not Operator (Reverses the condition)
is_raining = False
if not is_raining:
print("No need for an umbrella!")
else:
print("Don't forget your umbrella!")
# Combining with other operators
age = 15
has_permission = False
if not (age >= 18 or has_permission):
print("Access denied - too young and no permission!")
else:
print("Access granted!")
Complex Conditions
Real-Life Example: Job Application
age = 22
has_degree = True
has_experience = True
criminal_record = False
if (age >= 18 and age <= 65) and (has_degree or has_experience) and not criminal_record:
print("Congratulations! You're eligible for the job.")
if has_degree and has_experience:
print("You meet all preferred qualifications!")
elif has_degree or has_experience:
print("You meet minimum qualifications.")
else:
print("Sorry, you don't meet the requirements.")
if age < 18:
print("Reason: Too young")
elif criminal_record:
print("Reason: Background check failed")
else:
print("Reason: Missing qualifications")
Common Mistakes
1. Using = instead of ==
# ❌ Wrong - this assigns 5 to x, always True
x = 10
if x = 5: # SyntaxError!
print("This won't work")
# ✅ Correct - this compares x with 5
if x == 5:
print("x equals 5")
2. Forgetting colons
# ❌ Wrong - missing colon
age = 20
if age >= 18
print("Adult") # IndentationError!
# ✅ Correct
if age >= 18:
print("Adult")
3. Wrong indentation
# ❌ Wrong - inconsistent indentation
if age >= 18:
print("You can vote!")
print("This line is wrongly indented!") # IndentationError!
# ✅ Correct
if age >= 18:
print("You can vote!")
print("This line is properly indented!")
Practice Exercises
Exercise 1: Number Classifier
Write a program that classifies a number as positive, negative, or zero.
Exercise 2: BMI Calculator
Create a BMI calculator that gives health recommendations based on BMI categories.
Exercise 3: Leap Year Checker
Write a program that determines if a year is a leap year.
Exercise 4: Ticket Price Calculator
Calculate movie ticket prices based on age and day of the week.
Exercise 5: Password Strength Checker
Create a simple password strength checker with multiple criteria.
Summary
Conditional statements help your program make decisions:
if: Execute code if condition is trueelif: Check alternative conditionselse: Execute code if no conditions are true- Comparison operators:
==,!=,<,>,<=,>= - Logical operators:
and,or,not
Remember to:
- Use
==for comparison (not=) - Always use colons after conditions
- Maintain consistent indentation
- Test all branches of your conditions
Next: Loops - making your code repeat actions! 🔄