← Python lessons

Comparisons and Logical Operators

Part of a free Python course — sign up to save your progress and get AI hints.Sign up free

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)

This prints True, False, False, then True.

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 hold the same text:

name = "Ada"print(name == "Ada")print(name == "ada")

This prints True, then False. The comparison is case-sensitive, so "Ada" and "ada" are different.

Booleans stand on their own

Store a comparison in a variable. That variable goes straight into an if. You never need to write == True:

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

banked holds True, so the if runs.

Combine comparisons with and, or and not

  • and is True when both comparisons are True.
  • or is True when at least one comparison is True.
  • not flips True to False, and False to True.
score = 25attempts_left = 2print(score >= 20 and attempts_left > 0)print(score >= 30 or attempts_left > 0)print(not score >= 20)

This prints True, True, then False.

Write a full comparison on each side of and or or. To check a value is in a range, test both ends: score >= 0 and score <= 100.

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

Your turn

Print whether score is at least 20. Then print whether score is at least 10 and attempts_left is above 0.

🎯 Goal — make it print exactly:
False
True
score = 18attempts_left = 2# add two prints: one comparison, then one combined with and

Advanced reading