Python Conditionals
Learn to make decisions in your code using if/elif/else statements, comparison operators, and logical operators.
Making Decisions with if/elif/else
Conditional statements let your program make decisions. Python uses if, elif (else if), and else to execute different blocks of code depending on whether a condition is True or False.
score = 85
if score >= 90:
print("Grade: A - Outstanding!")
elif score >= 80:
print("Grade: B - Well done!")
elif score >= 70:
print("Grade: C - Good effort")
elif score >= 50:
print("Grade: D - Pass")
else:
print("Grade: F - Needs improvement")
Grade: B - Well done!Python checks each condition from top to bottom and runs the first one that is True.
Comparison and Logical Operators
Comparison operators compare two values and return True or False. Logical operators combine multiple conditions.
Comparison Operators
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater or equal
<= Less or equal
Logical Operators
and Both must be True
or At least one True
not Reverses True/False
age = 16
has_permit = True
# Using logical operators
if age >= 16 and has_permit:
print("You can drive with a supervisor")
elif age >= 16 and not has_permit:
print("Get your learner's permit first")
else:
print("You are not old enough to drive yet")
# Combining conditions
temp = 25
if temp > 30 or temp < 10:
print("Extreme weather!")
else:
print("Nice weather today")
Nested Conditions
You can place an if statement inside another if statement. This is called nesting. Be careful with indentation, as Python uses it to determine which code belongs to which block.
is_member = True
purchase_amount = 120
if is_member:
if purchase_amount >= 100:
discount = 20
print(f"Member with ${purchase_amount} purchase: {discount}% off!")
else:
discount = 10
print(f"Member discount: {discount}% off")
else:
if purchase_amount >= 100:
discount = 5
print(f"Non-member bulk discount: {discount}% off")
else:
discount = 0
print("No discount available")
Member with $120 purchase: 20% off!
Key Vocabulary
Conditional
A statement that executes code only when a specified condition is True.
Boolean Expression
An expression that evaluates to either True or False.
Comparison Operator
Symbols like ==, !=, >, < that compare two values.
Logical Operator
Keywords and, or, not that combine boolean conditions.
Worked Examples
Check if a number is positive, negative, or zero
number = -7
if number > 0:
print(f"{number} is positive")
elif number < 0:
print(f"{number} is negative")
else:
print("The number is zero")
Step 1: First check if number > 0. Since -7 is not > 0, this is False.
Step 2: Then check elif number < 0. Since -7 < 0, this is True.
Output: -7 is negative
Validate a password with multiple conditions
password = "Secure123"
has_upper = any(c.isupper() for c in password)
has_digit = any(c.isdigit() for c in password)
long_enough = len(password) >= 8
if has_upper and has_digit and long_enough:
print("Strong password!")
elif long_enough:
print("Weak password: add uppercase and numbers")
else:
print("Too short: must be at least 8 characters")
Step 1: We check three conditions: uppercase letters, digits, and length.
Step 2: The and operator ensures all three must be True. Output: Strong password!
Determine ticket price based on age and day
age = 16
day = "Tuesday"
if age < 5:
price = 0
category = "Free (under 5)"
elif age <= 17:
price = 12
category = "Child"
elif age >= 65:
price = 15
category = "Senior"
else:
price = 25
category = "Adult"
# Tuesday discount
if day == "Tuesday":
price = price * 0.5
print(f"{category} ticket on Tuesday: ${price:.2f} (half price!)")
else:
print(f"{category} ticket: ${price:.2f}")
Step 1: Age 16 matches the elif age <= 17 condition, so price = $12.
Step 2: It is Tuesday, so the price is halved. Output: Child ticket on Tuesday: $6.00 (half price!)
Knowledge Check
Select the correct answer for each question. Click "Check Answer" to see if you are right.
Question 1
What is the output of: if 10 > 5: print("Yes")?
Question 2
Which operator checks if two values are equal?
Question 3
What does True and False evaluate to?
Question 4
What does not True return?
Question 5
What keyword is used for "else if" in Python?
Key Concepts Summary
-
●
Use
if,elif, andelseto make decisions in your code. -
●
Comparison operators:
==,!=,>,<,>=,<=. -
●
Logical operators:
and(both True),or(at least one True),not(reverse). - ● Indentation matters in Python. Code inside an if block must be indented.
- ● Conditions can be nested by placing if statements inside other if statements.