Python Conditionals 🔀
Making Smart Decisions
Session 2: If, Elif, Else Logic
What Are Conditionals? 🤔
Conditionals are statements that let your program make decisions. "If
something is true, do this. Otherwise, do that."
Real-World Examples:
- If it's raining, bring an umbrella. Else, don't.
- If you're 13 or older, you can watch PG-13 movies. Else, watch G movies.
- If your password is correct, log in. Else, show error.
This is the foundation of how apps make decisions!
Comparison Operators 🔍
Before using if statements, you need to compare values. These operators check if something is true or
false:
Operators:
- == equal to (a == b)
- != not equal to (a != b)
- > greater than (a > b)
- < less than (a < b)
- >= greater than or equal (a >= b)
- <= less than or equal (a <= b)
Note: Use == to compare, not =
(which assigns values)
The If Statement 🚪
If a condition is true, execute code inside the if block.
Code Example:
age = 15
if age >= 13:
print("You can watch PG-13 movies!")
Notice: Code inside if is indented (pushed right).
Indentation matters in Python!
If-Else Statement 🔄
Do one thing if true, something else if false.
Code Example:
password = input("Enter password: ")
if password ==
"secret123":
print("Access granted!")
else:
print("Access denied!")
If password matches, print access granted. Otherwise, print denied.
Elif: Multiple Conditions 🌳
Elif (else if) lets you check multiple conditions. Check the first one,
then the next, etc.
Code Example - Grade Calculator:
score = int(input("Your score: "))
if score >= 90:
print("A -
Excellent!")
elif score >= 80:
print("B - Good job!")
elif score >=
70:
print("C - Okay")
else:
print("F - Need help")
Logic Operators: AND & OR 🔗
Combine multiple conditions with and and or. Remember logic gates?
AND - Both must be true:
age = 15
if age >= 13 and age < 18:
print("You are a
teenager!")
OR - At least one must be true:
if day == "Saturday" or day == "Sunday":
print("It's the
weekend!")
Smart Programs! 🎉
Your programs can now make decisions
Next Session: Loops - Making Programs Repeat