Conditional execution in Python directs program flow by evaluating Boolean expressions. Code blocks execute only when their associated condition resolves to True. In Python, any non-zero numerical value or non-empty sequence is considered True; zero, None, and empty sequences evaluate to False.
The foundational if-else construct has this syntax:
if condition:
# Code block for True condition
else:
# Code block for False condition
The else clause is optional. Indentation defines the scope of each block.
Example: Basic if-else
is_found = False
item_name = 'laptop'
if item_name == 'desktop':
is_found = True
print('Primary device located')
else:
print(f'Found item: {item_name}')
Relational operators like >, <, ==, >=, and <= are used to form conditions.
Handling Multiple Conditions with elif
For checking several distinct values, use elif (short for else-if).
score = 85
if score == 100:
grade = 'Perfect'
elif score >= 90:
grade = 'A'
elif score >= 80:
grade = 'B'
elif score >= 70:
grade = 'C'
else:
grade = 'Needs Improvement'
print(f'Grade: {grade}')
Python lacks a switch statement, making if-elif-else the standard for multi-branch logic.
Combining Conditions with Logical Operators
Use and and or to create compound conditions.
and: True only if all conditions are True.or: True if at least one condition is True.
value = 7
# Check if value is within a specific range
if value >= 1 and value <= 10:
print('Value is between 1 and 10')
# Check if value is outside a range
temperature = 25
if temperature < 15 or temperature > 30:
print('Temperature is uncomfortable')
else:
print('Temperature is acceptable')
# Complex condition with parentheses for clarity
id = 12
if (id >= 1 and id <= 5) or (id >= 10 and id <= 15):
print('ID is in the target groups')
Parentheses can explicitly define evaluation order. Relational operators (>, <, etc.) have higher precedence than and/or.
Single-Line Conditional Expression Simple conditionals can be written on one line.
counter = 50
if counter == 50: print('Counter is at midpoint')