CodeBlanks Logo Icon CodeBlanks

Logical

Learn boolean logic with and, or, not.

Logical operators

Logical operators combine bool values: and, or, not.

print(True and False)  # False
print(True or False)   # True
print(not True)        # False

and gives True only when both sides are True. or gives True when at least one side is True. not flips the value.

These operators are common in conditions: if age >= 18 and has_id:

Short circuit

Logical operators short circuit: when the result is determined, the other side is not evaluated.

False and expensive()   # expensive not called
True or expensive()      # expensive not called

False and ... is already False, the right side does not run. True or ... is already True, the right side does not run. This is useful for performance and safety.

Practice Print logical operations

Assign age = 20 and has_id = True. Print print(age >= 18 and has_id).

Starter code

main.py
# Logical operations

Sample solution

main.py
age = 20
has_id = True
print(age >= 18 and has_id)

Expected output

True

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the logical operator

Question
print(True ____ False)
Answer
print(True and False)

Explanation: and gives True when both sides are True.

2 What is True or False?

  • Error
  • False
  • True Correct answer
  • None

Explanation: or gives True when at least one is True.

3 Match the logical operators

Term Meaning
and Both True
or At least one True
not Flips
True True

All lessons in Beginner