5. and, or, not

Logical operators combine boolean expressions:

ExpressionResult
True and TrueTrue
True and FalseFalse
True or FalseTrue
False or FalseFalse
not TrueFalse
not FalseTrue

and, or and not are operators, not functions, so they are written between values or before one value.

Truthiness. Python treats some values as false in a boolean context:

  • Falsy: False, None, 0, 0.0, "", [], {}.
  • Truthy: every other value, for example 1, -5, "hi", [0].

bool() is a built-in function. Its signature is bool(value) and it converts any value to True or False using those rules. With no argument, bool() returns False.

When both operands are booleans, and and or return a boolean. With other values, they return one of the operands:

  • a or b returns a if a is truthy; otherwise it returns b.
  • a and b returns a if a is falsy; otherwise it returns b.

Python uses short-circuit evaluation: in A and B, if A is falsy, B is not evaluated; in A or B, if A is truthy, B is not evaluated.

Coming from JavaScript? Truthiness differs: [], {} and "" are falsy in Python but truthy in JS. a or b returns a when truthy, like ||, but there is no ??: or also falls back on empty values.

#01

Combine with and

Use the and operator to combine the comparisons 5 > 3 and 2 < 4, and print the result. and is True only when both comparisons are True.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#02

Combine with or

Use the or operator to combine the comparisons 5 < 3 and 2 < 4, and print the result. or is True when at least one comparison is True.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#03

Negate a comparison

Use the not operator before the comparison 5 > 3, and print the result. not flips the boolean value.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#04

Check truthiness

Use the built-in bool() on these four values in this order: 0, 1, "", "hi". Print the four results in one print() call, separated by commas.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#05

Use or as a default

Store an empty string in a variable named name. Print name or "Anonymous". Because name is falsy, or returns the right operand.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#06

Return an operand with and

Print the result of 1 and "ready". Because 1 is truthy, and returns the right operand.

Print exactly:

Create a free account to save your progress and unlock chapter 2.