Python Conditional Statements
Introduction
Conditional statements are the decision-makers in programming. They allow your program to behave differently based on different conditions, essentially enabling your code to make decisions. In Python, these decisions are primarily implemented using if
, elif
(short for "else if"), and else
statements.
Think of conditional statements as the crossroads in your code's journey. Based on certain conditions, your program will take different paths, executing specific blocks of code while skipping others.
Basic Syntax of Conditional Statements
The if
Statement
The most fundamental conditional statement in Python is the if
statement. It evaluates a condition and executes a block of code if that condition is True
.
if condition:
# Code to execute if the condition is True
Here's a simple example:
age = 18
if age >= 18:
print("You are eligible to vote!")
Output:
You are eligible to vote!
In this example, the code checks if age
is greater than or equal to 18. Since the condition is True
, the print statement executes.
The else
Statement
The else
statement provides an alternative block of code to execute when the if
condition is False
.
if condition:
# Code to execute if the condition is True
else:
# Code to execute if the condition is False
Let's extend our voting example:
age = 16
if age >= 18:
print("You are eligible to vote!")
else:
print("Sorry, you are not eligible to vote yet.")
Output:
Sorry, you are not eligible to vote yet.
The elif
Statement
Short for "else if," the elif
statement allows you to check multiple conditions in sequence.
if condition1:
# Code to execute if condition1 is True
elif condition2:
# Code to execute if condition1 is False and condition2 is True
else:
# Code to execute if both condition1 and condition2 are False
Example with multiple conditions:
score = 85
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
elif score >= 60:
print("Grade: D")
else:
print("Grade: F")
Output:
Grade: B
Nested Conditional Statements
You can place conditional statements inside other conditional statements, creating nested conditions.
temperature = 25
humidity = 80
if temperature > 30:
print("It's hot outside!")
if humidity > 60:
print("And it's humid too!")
else:
print("Temperature is moderate.")
if humidity > 60:
print("But it's quite humid.")
Output:
Temperature is moderate.
But it's quite humid.
Logical Operators with Conditionals
Python provides logical operators to combine multiple conditions:
and
: Both conditions must beTrue
or
: At least one condition must beTrue
not
: Inverts the condition (makesTrue
intoFalse
and vice versa)
username = "admin"
password = "12345"
if username == "admin" and password == "12345":
print("Login successful")
else:
print("Invalid credentials")
Output:
Login successful
Using or
:
day = "Saturday"
if day == "Saturday" or day == "Sunday":
print("It's the weekend!")
else:
print("It's a weekday.")
Output:
It's the weekend!
Using not
:
is_raining = False
if not is_raining:
print("No need for an umbrella!")
else:
print("Take an umbrella!")
Output:
No need for an umbrella!
Conditional Expressions (Ternary Operator)
Python offers a shorthand way to write simple conditional statements using the ternary operator:
# Syntax: value_if_true if condition else value_if_false
Example:
age = 20
status = "Adult" if age >= 18 else "Minor"
print(status)
Output:
Adult
This is equivalent to:
age = 20
if age >= 18:
status = "Adult"
else:
status = "Minor"
print(status)
Real-World Applications
1. Authentication System
def authenticate_user():
username = input("Enter username: ")
password = input("Enter password: ")
stored_username = "user123"
stored_password = "pass456"
if username == stored_username and password == stored_password:
print("Authentication successful!")
return True
else:
print("Invalid username or password!")
return False
# Testing the function
authenticate_user()
If you enter "user123" as username and "pass456" as password, the output will be:
Authentication successful!
Otherwise:
Invalid username or password!
2. Temperature Converter with Validation
def convert_temperature():
temp_str = input("Enter temperature (e.g., '32F' or '0C'): ")
if len(temp_str) < 2:
print("Invalid format. Use format like '32F' or '0C'.")
return
try:
temp = float(temp_str[:-1])
unit = temp_str[-1].upper()
if unit == 'C':
result = (temp * 9/5) + 32
print(f"{temp}°C is equal to {result:.1f}°F")
elif unit == 'F':
result = (temp - 32) * 5/9
print(f"{temp}°F is equal to {result:.1f}°C")
else:
print("Invalid unit. Use 'C' for Celsius or 'F' for Fahrenheit.")
except ValueError:
print("Invalid temperature. Please enter a number followed by 'C' or 'F'.")
# Testing the function
convert_temperature()
If you enter "32F", the output will be:
32.0°F is equal to 0.0°C
3. Simple Menu System
def display_menu():
print("\n=== Main Menu ===")
print("1. View Profile")
print("2. Edit Settings")
print("3. Help")
print("4. Exit")
choice = input("\nEnter your choice (1-4): ")
if choice == '1':
print("Viewing your profile...")
elif choice == '2':
print("Opening settings menu...")
elif choice == '3':
print("Displaying help documentation...")
elif choice == '4':
print("Exiting program. Goodbye!")
else:
print("Invalid choice. Please select a number between 1 and 4.")
# Testing the function
display_menu()
Additional Techniques
Using in
with Conditionals
The in
operator checks if a value exists in a sequence (like a list, tuple, or string):
fruits = ["apple", "banana", "cherry"]
if "banana" in fruits:
print("Yes, banana is a fruit!")
Output:
Yes, banana is a fruit!
Truth Value Testing
In Python, values are inherently considered True
or False
in a boolean context:
- Empty sequences (lists, tuples, strings, etc.) are considered
False
- Zero in any numeric type is considered
False
None
is consideredFalse
- Everything else is generally considered
True
# Examples
if []:
print("This won't print because an empty list is False")
if 0:
print("This won't print because 0 is False")
if "Hello":
print("This will print because a non-empty string is True")
Output:
This will print because a non-empty string is True
Common Pitfalls and Best Practices
1. Using ==
vs. is
The ==
operator compares values, while is
compares identities (if they're the same object):
a = [1, 2, 3]
b = [1, 2, 3]
print(a == b) # True - same values
print(a is b) # False - different objects
Output:
True
False
2. Be Careful with Mutable Default Arguments
# Problematic
def add_item(item, list=[]):
list.append(item)
return list
print(add_item("apple")) # ['apple']
print(add_item("banana")) # ['apple', 'banana'] (not what you might expect)
# Better approach
def add_item_better(item, list=None):
if list is None:
list = []
list.append(item)
return list
print(add_item_better("apple")) # ['apple']
print(add_item_better("banana")) # ['banana']
3. Using Multiple Conditions Efficiently
# Less efficient (evaluates all conditions)
if x > 0 and x < 10 and x % 2 == 0:
print("x is a positive even number less than 10")
# More efficient (short-circuit evaluation)
if 0 < x < 10 and x % 2 == 0:
print("x is a positive even number less than 10")
Summary
Conditional statements are fundamental building blocks in Python programming that allow your code to make decisions based on different conditions:
if
statements execute code when a condition is trueelif
statements provide additional conditions to checkelse
statements provide a fallback when no conditions are met- Logical operators (
and
,or
,not
) allow combining or inverting conditions - The ternary operator provides a concise way to write simple conditional expressions
Mastering conditional statements is essential for writing dynamic and responsive programs that can adapt to different inputs and situations.
Practice Exercises
- Basic Condition: Write a program that checks if a number is positive, negative, or zero.
- Grade Calculator: Create a function that takes a numerical score and returns the corresponding letter grade.
- Leap Year Checker: Write a program that determines if a given year is a leap year.
- Discount Calculator: Create a function that calculates the final price after applying discounts based on the purchase amount.
- Simple Calculator: Implement a basic calculator that performs different operations (+, -, *, /) based on user input.
Additional Resources
- Official Python Documentation on Control Flow
- Python Conditional Statements (W3Schools)
- Python Practice Problems (HackerRank)
- Python Principles: Conditionals
Remember, practice is key to mastering conditional statements. Start with simple conditions and gradually work your way up to more complex decision-making logic in your programs.
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)