Course Content
Conditional Statements in Python
Conditional Statements in Python
Introduction to if-elif-else Statement
The if-elif-else
statement is a powerful tool in Python that allows you to check multiple conditions and execute different blocks of code based on which condition is true. It is particularly useful when you have multiple conditions to evaluate, but only want one block of code to run.
When you need to choose between several conditions, elif
is preferred over multiple if
statements. This is because elif
ensures that once a condition is met, the rest of the conditions are skipped, improving efficiency. In contrast, using multiple if
statements results in all conditions being evaluated independently, which can lead to unnecessary checks and redundant code.
Let's track a user's sleep duration and categorize it into different ranges. We will check whether the user has met their sleep goal, is close to meeting it, or needs more rest.
hours_slept = 6 sleep_goal = 8 if hours_slept < 0: print("Sleep hours cannot be negative.") if hours_slept >= sleep_goal: print("Great job! You've met your sleep goal!") if hours_slept >= sleep_goal - 2: print("You're almost there! Keep going, you'll reach your goal soon!") if hours_slept < sleep_goal - 2: print("You need more rest. Try to sleep a bit longer tonight.")
In this version, all conditions are evaluated independently, even if one condition is already true. This leads to redundant checks. For example, if the user has already met their goal, the code still checks if they're close to the goal or need more rest.
hours_slept = 6 sleep_goal = 8 if hours_slept < 0: print("Sleep hours cannot be negative.") elif hours_slept >= sleep_goal: print("Great job! You've met your sleep goal!") elif hours_slept >= sleep_goal - 2: print("You're almost there! Keep going, you'll reach your goal soon!") else: print("You need more rest. Try to sleep a bit longer tonight.")
Using elif
helps make the code more readable and efficient, as once a condition is met, no further conditions need to be checked.
This diagram visualizes the flow of an if-elif-else
decision structure in Python. The process starts by evaluating the initial if
condition:
- If the first condition is true, the code inside the
if
block executes; - If the first condition is false, it moves to the next condition, which is the
elif
. If theelif
condition is true, the correspondingelif
block is executed; - If the first
elif
is false, anotherelif
can be checked, and if it's true, its respective code block runs; - If none of the
if
orelif
conditions are met (i.e., all are false), the finalelse
block is executed, ensuring one code block is always run.
This flow ensures that only the first true condition is executed, providing a clean and efficient way to handle multiple conditions. The if-elif-else
structure avoids redundant checks, and only one code block is executed from the entire structure.
Thanks for your feedback!