5. Logical operators
Logical operators combine or invert booleans:
| Expression | Result |
|---|---|
True and True | True |
True and False | False |
True or False | True |
False or False | False |
not True | False |
not False | True |
andisTrueonly when both operands areTrue.orisTruewhen at least one operand isTrue.notflips one boolean:TruebecomesFalseand vice versa.
Python uses short-circuit evaluation: in A and B, if A is False, B is not evaluated; in A or B, if A is True, B is not evaluated. The result is still a boolean.
and, or and not are operators, not functions, so they are written between values (True and False) or before one value (not True).
input() returns text, so comparing its result produces a boolean:
has_license is True when the user types yes, and False otherwise.
Coming from JavaScript? and, or and not replace &&, || and !. They short-circuit like their JS counterparts, but they can return an operand instead of a boolean.
Both must be true
Use the and operator with True and False, and print the result. and gives True only when both values are True.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
At least one is true
Use the or operator with True and False, and print the result. or gives True when at least one value is True.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Negate a boolean
Use the not operator before True, and print the result. not flips the value.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Combine a comparison and a boolean
Read an age with input("Age: ") and convert it with int(). Read the answer to input("License? (yes/no): ") and turn it into a boolean by comparing it with "yes", as shown in the lesson.
If the person is 18 or older and has a license, print Drive; otherwise, print No drive.
The simulated user types 20 and then yes.
Print exactly:
Create a free account to save your progress and unlock chapter 2.