8. Conditional Statements (if, elif, else)
Conditional statements allow your Python program to make decisions. Instead of running code from top to bottom without thinking, conditions allow the program to choose different actions based on data.
1) The Basic if Statement
The if statement runs a block of code only if the condition is True.
age = 20
if age >= 18:
print("You are an adult.")
If the condition age >= 18 is True, Python executes the indented block.
If it is False, nothing happens.
2) Using else
The else block runs when the if condition is False.
age = 16
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
3) Using elif (Multiple Conditions)
The elif statement allows you to check multiple conditions.
score = 75
if score >= 90:
print("Excellent")
elif score >= 70:
print("Good")
elif score >= 50:
print("Pass")
else:
print("Fail")
Python checks conditions from top to bottom. Once it finds a True condition, it stops checking.
4) Comparison Operators in Conditions
Conditions use comparison operators:
==Equal to!=Not equal to>Greater than<Less than>=Greater or equal<=Less or equal
number = 10
if number == 10:
print("Number is exactly 10")
5) Logical Operators in Conditions
You can combine multiple conditions using logical operators.
age = 25
has_id = True
if age >= 18 and has_id:
print("Access granted")
- and → both conditions must be True
- or → at least one condition must be True
- not → reverses the condition
6) Nested Conditions
You can place an if inside another if.
age = 20
is_member = True
if age >= 18:
if is_member:
print("Discount applied")
else:
print("No membership discount")
7) Short Conditional (Ternary Operator)
Python allows short conditions in one line.
age = 20
message = "Adult" if age >= 18 else "Minor"
print(message)
8) Common Beginner Mistakes
- Using
=instead of== - Indentation errors
- Forgetting to convert input to int()
- Incorrect logical operator usage
Conclusion
Conditional statements are fundamental in Python programming. They allow your applications to respond dynamically to user input, system state, and data values.
Mastering if, elif, and else
prepares you for more advanced logic such as loops, functions,
and real-world application development.