Combining Boolean Values with and, or Operators
In this lesson, we will take a closer look at the and
and or
operators.
and Operator
The and
operator returns true only when all the conditions on both sides are true.
is_admin = True is_logged_in = True # When the user is an admin and logged in print(is_admin and is_logged_in) # True
In the example above, is_admin and is_logged_in
returns true only when the user is both an admin (is_admin
) and logged in (is_logged_in
).
The and
operator is used when multiple conditions must be met simultaneously.
or Operator
The or
operator returns true if at least one of the conditions on either side is true.
is_admin = True has_permission = False # When the user is either an admin or has permission print(is_admin or has_permission) # True
In the example above, is_admin or has_permission
returns true when the user is either an admin (is_admin
) or has permission (has_permission
).
The or
operator is used when only one of several conditions needs to be met.
Using and, or Operators Together
You can combine multiple conditions using and
and or
operators as follows:
is_admin = True is_logged_in = True has_permission = False # When the user is an admin and logged in, or has permission is_allowed = (is_admin and is_logged_in) or has_permission print(is_allowed) # True
In the example, the is_allowed
variable returns true when is_admin
is true and is_logged_in
is true, or when has_permission
is true.
Which of the following statements about the and
operator is correct?
Returns true if at least one condition is true.
Returns true when all conditions are false.
Returns true only when all conditions are true.
Returns true if at least one condition is false.
Lecture
AI Tutor
Publish
Design
Upload
Notes
Favorites
Help
Code Editor
Execution Result