Introduction to Conditionals
Conditional statements allow your program to execute certain pieces of code based on specific conditions. They enable decision-making capabilities in your code.
Basic if
Statement
Indentation Notice
Take note of the indentation after :
age = 20
if age >= 18:
print("You are eligible to vote.")
Output:
You are eligible to vote.
if...else
Statement
The if...else
statement executes one block of code if a condition is true and another block if it is false.
temperature = 15
if temperature > 20:
print("It's warm outside.")
else:
print("It's cold outside.")
Output:
It's cold outside.
if...elif...else
Statement
For multiple conditions, use elif
(short for "else if").
score = 85
if score >= 90:
grade = 'A'
elif score >= 80:
grade = 'B'
elif score >= 70:
grade = 'C'
else:
grade = 'D'
print(f"Your grade is {grade}.")
Output:
Your grade is B.
Nested Conditionals
Conditionals can be nested within each other for more complex logic.
username = "admin"
password = "1234"
if username == "admin":
if password == "1234":
print("Access granted.")
else:
print("Incorrect password.")
else:
print("Username not recognized.")
Output:
Access granted.
Comparison Operators
Comparison operators compare two values:
==
Equal to!=
Not equal to>
Greater than<
Less than>=
Greater than or equal to<=
Less than or equal to
Example
budget = 500
price = 450
if price <= budget:
print("You can purchase this item.")
else:
print("This item is too expensive.")
Output:
You can purchase this item.
Logical Operators
Logical operators combine multiple conditions:
and
True if both conditions are trueor
True if at least one condition is truenot
Inverts the truth value
Using and
age = 25
has_license = True
if age >= 18 and has_license:
print("You can drive.")
else:
print("You cannot drive.")
Output:
You can drive.
Using or
has_ticket = False
is_on_guest_list = True
if has_ticket or is_on_guest_list:
print("You may enter the concert.")
else:
print("You cannot enter the concert.")
Output:
You may enter the concert.
Using not
is_raining = False
if not is_raining:
print("No need for an umbrella.")
Output:
No need for an umbrella.
Membership Operators
Membership operators test for membership in a sequence:
in
True if value is in sequencenot in
True if value is not in sequence
Example with in
available_colors = ['red', 'green', 'blue']
if 'green' in available_colors:
print("Green color is available.")
Output:
Green color is available.
Example with not in
blocked_users = ['user123', 'badguy']
current_user = 'john_doe'
if current_user not in blocked_users:
print("Access granted.")
else:
print("Access denied.")
Output:
Access granted.
Identity Operators
Identity operators compare the memory locations of two objects:
is
True if both variables point to the same objectis not
True if variables point to different objects
Example
a = [1, 2, 3]
b = a
c = [1, 2, 3]
print(a is b) # True
print(a is c) # False
Output:
True
False
Ternary Conditional Operator
A one-line if...else
statement.
status = "Success" if operation_completed else "Failed"
print(status)
Real-World Example
age = 17
message = "Eligible to vote" if age >= 18 else "Not eligible to vote"
print(message)
Output:
Not eligible to vote
Combining Conditions
You can combine multiple conditions using logical operators.
day = "Saturday"
time = 14
if day in ["Saturday", "Sunday"] and 9 <= time <= 17:
print("The store is open.")
else:
print("The store is closed.")
Output:
The store is open.
Short-Circuit Evaluation
Python stops evaluating conditions as soon as the result is determined.
def check_user(user):
print("Checking user...")
return user == "admin"
def check_password(pwd):
print("Checking password...")
return pwd == "secret"
if check_user("admin") and check_password("secret"):
print("Access granted.")
Output:
Checking user...
Checking password...
Access granted.
Real-World Examples
Email Validation
email = "[email protected]"
if "@" in email and "." in email:
print("Valid email address.")
else:
print("Invalid email address.")
Output:
Valid email address.
Shopping Cart Discount
cart_total = 120
is_member = True
if cart_total > 100 or is_member:
print("You qualify for free shipping.")
else:
print("Shipping charges apply.")
Output:
You qualify for free shipping.
Password Strength Checker
password = "Password123!"
if len(password) >= 8:
if any(char.isdigit() for char in password):
if any(char.isupper() for char in password):
if any(not char.isalnum() for char in password):
print("Strong password.")
else:
print("Password should include a special character.")
else:
print("Password should include an uppercase letter.")
else:
print("Password should include a number.")
else:
print("Password should be at least 8 characters long.")
Output:
Strong password.
Traffic Light System
light_color = "Yellow"
if light_color == "Green":
action = "Go"
elif light_color == "Yellow":
action = "Slow down"
elif light_color == "Red":
action = "Stop"
else:
action = "Proceed with caution"
print(f"The light is {light_color}. You should {action}.")
Output:
The light is Yellow. You should Slow down.
The pass
Statement
Used when a statement is syntactically required but you don't want any command to execute.
if False:
pass # Placeholder for future code
else:
print("This will execute.")
Output:
This will execute.
The match
Statement (Python 3.10+)
Pattern matching allows for cleaner syntax when matching against multiple possibilities.
command = "pause"
match command:
case "start":
print("Starting the system.")
case "stop":
print("Stopping the system.")
case "pause":
print("Pausing the system.")
case _:
print("Unknown command.")
Output:
Pausing the system.