5. Logical operators

Logical operators combine or invert booleans:

ExpressionResult
True and TrueTrue
True and FalseFalse
True or FalseTrue
False or FalseFalse
not TrueFalse
not FalseTrue
  • and is True only when both operands are True.
  • or is True when at least one operand is True.
  • not flips one boolean: True becomes False and 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.

#01

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.

#02

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.

#03

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.

#04

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.