In Python, the if, elif, and else statements form the backbone of decision-making and control flow. They allow your program to choose between different paths based on conditions.
Basic Structure
if condition1:
# do something
elif condition2:
# do something else
else:
# fallback optionExample 1: Basic if
temperature = 35
if temperature > 30:
print("It's a hot day")Since the condition is true, the message is printed.
Example 2: if-else
age = 17
if age >= 18:
print("You can vote")
else:
print("You are underage")Only one of the blocks runs depending on the condition.
Example 3: if-elif-else
marks = 82
if marks >= 90:
print("Grade: A")
elif marks >= 75:
print("Grade: B")
elif marks >= 60:
print("Grade: C")
else:
print("Grade: D")Multiple levels of conditions handled cleanly.
Example 4: Nested if
score = 92
if score > 50:
if score > 90:
print("Excellent!")
else:
print("Good job!")Nested conditions provide finer control.
Example 5: Multiple Conditions using and
age = 22
has_id = True
if age >= 18 and has_id:
print("Entry granted")Both conditions must be true for this to run.
Example 6: Multiple Conditions using or
is_student = False
is_senior = True
if is_student or is_senior:
print("You get a discount")Only one condition needs to be true.
Example 7: Using not in Conditions
logged_in = False
if not logged_in:
print("Please log in first")not reverses the condition.
Example 8: String Comparison
answer = "yes"
if answer == "yes":
print("Proceeding...")String comparisons are case-sensitive.
Example 9: elif Ladder
day = "Wednesday"
if day == "Monday":
print("Start of the week")
elif day == "Wednesday":
print("Midweek hustle")
elif day == "Friday":
print("Almost weekend")
else:
print("Just another day")Perfect for menu or option selections.
Example 10: Boolean Flags
is_admin = True
if is_admin:
print("Access to admin panel")
else:
print("Limited access")Booleans are often used directly in control statements.
Key Takeaways
- Use
ifto check conditions. - Use
eliffor additional checks if the first is false. - Use
elseas a fallback when no conditions match. - Maintain proper indentation — Python depends on it for code blocks.
- Group complex conditions using logical operators like
and,or, andnot.
Mastering if, elif, and else is crucial for building interactive, intelligent Python programs that respond dynamically to inputs and data.
