Conditional statements
Imagine writing a story where the next part depends on the reader’s choice. Conditional statements in Python work similarly. They let you tell the computer, “If this happens, do that. Otherwise, do something else.” This lets your program respond dynamically to different situations.
What are conditional statements?
Conditional statements are used to control the flow of your program by setting rules for what should happen under different circumstances. Python uses if
elif
else
The if
statement: Asking "What If?"
if
The if
if
block runs; if not, Python skips it.
temperature = 30
if temperature > 25:
print("It's a warm day!")
Explanation: If the temperature
is greater than 25, the program prints "It's a warm day!" Otherwise, it skips this block.
The else
statement: The backup plan
else
The else
if
else
temperature = 15
if temperature > 25:
print("It's a warm day!")
else:
print("It's a cool day.")
Explanation: If the temperature
is not greater than 25, Python prints "It's a cool day." The else
if
The elif
statement: Checking additional conditions
elif
The elif
temperature = 20
if temperature > 25:
print("It's a warm day!")
elif temperature > 15:
print("It's a mild day.")
else:
print("It's a cool day.")
Explanation: Python checks the conditions in order:
1. If the temperature
is greater than 25, it prints "It's a warm day!"
2. If not, it checks if the temperature
is greater than 15. If true, it prints "It's a mild day."
3. If none of these conditions are true, it prints "It's a cool day."
How if
, elif
, and else
work together
if
elif
else
1. Python checks the if
2. If the if
3. If the if
elif
4. If no conditions are true, the else
Examples of conditional statements
Example 1: Even or Odd numbers
number = 7
if number % 2 == 0:
print("It's an even number!")
else:
print("It's an odd number!")
Explanation: The program checks if the number is divisible by 2 with no remainder (number % 2 == 0
). If true, it’s even; otherwise, it’s odd.
Example 2: A grading system
grade = 85
if grade >= 90:
print("A")
elif grade >= 80:
print("B")
elif grade >= 70:
print("C")
else:
print("D")
Explanation: The program checks the score range and assigns a grade:
- If the score is 90 or above, it prints "A".
- If the score is between 80 and 89, it prints "B".
- If the score is between 70 and 79, it prints "C".
- If the score is below 70, it prints "D".
Best practices for writing conditional statements
-
Keep conditions clear: Write conditions that are easy to understand.
# Good if age >= 18: print("Adult") # Confusing if not (age < 18): print("Adult")
-
Avoid redundant checks: Use
instead of multipleelif
statements.if
# Good if score >= 90: print("A") elif score >= 80: print("B") # Inefficient if score >= 90: print("A") if score >= 80 and score < 90: print("B")
-
Use descriptive variables: Make your code readable by choosing meaningful variable names.
temperature = 30 # Clear t = 30 # Vague
Conclusion
Conditional statements (if
elif
else