- Use the
andkeyword to check if two conditions are both true. - Use the
orkeyword to check if at least one of two conditions is true. - Use the
notkeyword to invert a Boolean value.
Building More Complex Questions
Simple comparisons are great, but the real world is more complex. We often need to check multiple conditions at once. Python gives us three Logical Operators to combine our Boolean expressions: and, or, and not.
The and Operator
The and operator is used when you need to make sure that both (or all) conditions are True. If even one of them is False, the entire expression becomes False.
Example: Let's check if a grade is a 'B' (between 70 and 79).
grade = 75
if grade >= 70 and grade < 80:
print("This is a B.")
The or Operator
The or operator is used when you only need at least one of the conditions to be True. The entire expression is only False if all the conditions are False.
Example: Let's check if it's the weekend.
day = "Saturday"
if day == "Saturday" or day == "Sunday":
print("It's the weekend!")
The not Operator
The not operator is the simplest. It just inverts or "flips" a Boolean value. It turns True into False and False into True.
is_raining = False
if not is_raining:
print("It's not raining, let's go outside!")
Live Example: The Login System
This Trinket demonstrates all three operators in a simple "login" scenario. Run it, then go into the code and change the values of the variables (username, password, is_logged_in, etc.) to see how the output changes!
Logical operators are what allow us to build precise and complex rules into our programs. These will be incredibly important when we start working with loops in our next lesson.
Interactive Sandbox
Use this space to practice writing code and complete the "Your Turn" activities above.