← Python lessons

Comparisons and Logical Operators

A boolean is one of just two values: True or False. Comparisons produce booleans, and booleans drive every decision your program makes.

The two boolean values

is_ready = True
game_over = False

Note the capital letters and no quotes — True is the boolean, "True" is text.

Comparison operators

Each of these asks a question and gives back True or False:

  • == equal to
  • != not equal to
  • > greater than, < less than
  • >= greater than or equal to, <= less than or equal to
print(5 == 5)
print(5 != 5)
print(10 >= 20)
print(3 < 7)

Watch out: == compares, = assigns. x = 5 stores 5 in x; x == 5 asks whether x equals 5.

Comparing text

Use == to check whether two strings contain the same text:

name = "Ada"
if name == "Ada":
    print("Welcome back!")
else:
    print("Hello, new visitor!")

The comparison is case-sensitive: "Ada" == "ada" is False. Use = to assign the name, and == to compare it.

Booleans stand on their own

Store a comparison in a variable, and that variable goes straight into an if — you never need to write == True:

score = 25
banked = score >= 20
print(banked)
if banked:
    print("done for this round")

banked holds True, so the if runs.

See also: if, elif, else, Membership Testing.

Your turn

Add two lines: print whether score is at least 20, then print whether it is not equal to 0.

score = 18
# add two prints: one comparison each

Expected output

False
True

Combine comparisons with and, or and not

  • and is true when both conditions are true.
  • or is true when at least one condition is true.
  • not reverses a condition's truth value.

These descriptions apply to Boolean conditions. Python can also use and and or with other values, but that is beyond this introduction.

score = 25
attempts_left = 2
print(score >= 20 and attempts_left > 0)
print(score >= 30 or attempts_left > 0)
print(not (score >= 20))

The results are True, True, then False. Parentheses make grouping clear when combining several conditions.

Write a complete comparison on each side

To accept either 1 or 2, write choice == 1 or choice == 2. Writing choice == 1 or 2 does not repeat the comparison: the non-zero number 2 makes that condition truthy regardless of choice.

Python uses the words and, or, not, rather than && or ||. For a value inside a range, both boundaries must hold: age >= 12 and age <= 18.

Your turn: combine two questions

Print whether the player has at least 20 points and at least one attempt left.

score = 25
attempts_left = 2
# Print one combined comparison.

Expected output

True

See also: if, elif, else, Data Validation.


Practise this in the free Python course, where every exercise checks your code instantly.