Python Conditional Statements
By Seokhyeon Byun 4 min read
Note: This post is based on my old programming study notes when I taught myself.
Basic Syntax
if condition_1:
Statement_1
elif condition_2:
Statement_2
else:
Statement_3
If condition_1 is True, then execute Statement_1. If both condition_1 and condition_2 are False, then execute Statement_3. elif can be used multiple times if required.
Important Notes
- Always be careful with indentation - Python uses indentation to define code blocks
- Colon at the end of condition - Each condition line must end with
:
# Example
age = 18
if age >= 18:
print("You are an adult")
elif age >= 13:
print("You are a teenager")
else:
print("You are a child")
Comparison Operators
| Operator | Description |
|---|---|
x < y | Less than |
x > y | Greater than |
x == y | Equal to |
x != y | Not equal to |
x >= y | Greater than or equal to |
x <= y | Less than or equal to |
# Examples
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "F"
Logical Operators
and, or, not
| Operator | Description |
|---|---|
x and y | Both x and y are True, then True |
x or y | Either x or y is True, then True |
not x | If x is False, then True |
# Examples
temperature = 75
sunny = True
if temperature > 70 and sunny:
print("Perfect weather for a picnic!")
if temperature < 32 or temperature > 100:
print("Extreme weather conditions")
if not sunny:
print("Don't forget your umbrella")
Membership Operators
in, not in
x in [List/Tuple/String]x not in [List/Tuple/String]
# Examples
fruits = ['apple', 'banana', 'orange']
favorite = 'apple'
if favorite in fruits:
print("Your favorite fruit is available")
if 'grape' not in fruits:
print("We don't have grapes")
# String membership
text = "Hello World"
if 'World' in text:
print("Found 'World' in the text")
pass Statement
When we want “Nothing to happen for a certain condition”, use pass.
names = ['Bruce', 'James', 'Bobby', 'Jessica']
if 'Jessica' in names:
pass # Do nothing
else:
print('There is a stranger in our crew.')
Explanation: If Jessica is in the names list, then nothing happens. If the name is not in the list, execute the else part.
# Another example - placeholder for future code
def process_data(data):
if len(data) > 100:
pass # Placeholder for large-dataset handling
else:
print("Processing small dataset")
One-line if Statement
If the statement after condition is just one line, we can write the if condition and statement on one line.
pocket = ['iPhone', 'money', 'apple']
if 'money' in pocket: pass
else: print("Show me your money")
# More practical examples
age = 20
print("Adult") if age >= 18 else print("Minor")
# Or with variables
status = "eligible" if age >= 18 else "not eligible"
Conditional Expression (Ternary Operator)
Traditional way:
if score >= 90:
message = "Pass"
else:
message = "Fail"
Using conditional expression:
message = "Pass" if score >= 90 else "Fail"
More examples:
# Determine absolute value
number = -5
absolute = number if number >= 0 else -number
# Set default value
username = input_name if input_name else "Anonymous"
# Choose maximum
maximum = a if a > b else b
# Nested conditional expressions
grade = "A" if score >= 90 else "B" if score >= 80 else "C" if score >= 70 else "F"
Common Patterns
Multiple Conditions
# AND conditions
if age >= 18 and has_license and has_insurance:
print("You can drive")
# OR conditions
if payment_method == "cash" or payment_method == "card" or payment_method == "digital":
print("Payment accepted")
# Better way for OR with multiple values
if payment_method in ["cash", "card", "digital"]:
print("Payment accepted")
Range Checking
# Check if number is in range
number = 75
if 0 <= number <= 100:
print("Number is within valid range")
# Grade boundaries
if 90 <= score <= 100:
grade = "A"
elif 80 <= score < 90:
grade = "B"
elif 70 <= score < 80:
grade = "C"
Truthy and Falsy Values
# These evaluate to False
empty_list = []
empty_string = ""
zero = 0
none_value = None
if not empty_list:
print("List is empty")
# These evaluate to True
non_empty_list = [1, 2, 3]
non_empty_string = "hello"
non_zero = 42
if non_empty_list:
print("List has items")
---