Course Content
Conditional Statements in Python
Conditional Statements in Python
Logical Operators
Previously, we explored situations involving a single condition in the if statement. Now, let's delve into scenarios where we need to evaluate multiple conditions.
Nested if Statements
One approach is to use nested if
statements, as demonstrated in the example:
steps_taken = 8000 calories_burned = 300 if steps_taken >= 5000: if calories_burned >= 500: print("Excellent work! You hit your daily fitness goals.")
However, relying heavily on nested if
conditions is not considered best practice. A seasoned developer would prefer to use logical operators instead of nesting conditions.
Using Logical Operators
Logical operators allow us to combine multiple conditions more efficiently.
Python language has three logical operators: not
, and
, or
.
steps_taken = 8000 calories_burned = 300 if steps_taken >= 5000 and calories_burned >= 500: print("Excellent work! You hit your daily fitness goals.")
The not Operator
not
is applied to one condition and inverts its value.
steps_taken = 0 if not steps_taken: print("No steps recorded yet. Time to get moving!")
Logical and
Condition with and
works only if both conditions are True
.
steps_taken = 8000 calories_burned = 600 hydration_level = 2 if steps_taken >= 5000 and calories_burned >= 500 and hydration_level >= 2: print("Amazing! You've achieved all your fitness goals for the day.")
Logical or
Condition with or
works if at least one of the two (or more) specified conditions is True
.
Suppose you want to celebrate small wins. If you meet at least one of your goals, print a motivational message.
steps_taken = 8000 calories_burned = 200 hydration_level = 2 if steps_taken >= 10000 or calories_burned >= 500 or hydration_level >= 2: print("Great job! You're making progress on your fitness journey.")
Here, the hydration_level
meets the condition, so the if
statement executes. Remember, with the or
operator, only one condition needs to be True
.
1. In a fitness tracker app, you want to check if a user meets their daily step goal and calorie goal. Which logical operator should you use?
2. How would you check if the user meets at least one of their fitness goals?
Thanks for your feedback!