Comparison and logical operators

Definition

Comparison operators are used to compare two values and give a result of True or False.

Comparison operators

For the examples below, assume that a = 15 and b = 10

Symbol Meaning Example Result
== Equal to a == b False
!= Not equal to a != b True
> Greater than a > b True
< Less than a < b False
>= Greater than or equal to a >= b True
<= Less than or equal to a <= b False

Logical operators

Logical operators will always result in a result of True or False. For the examples below, assume that a = True and b = False.

Symbol Meaning Example Result
and Both expressions are True a and b False
or At least one of the expressions is True a or b True
not The expression is not True not a False

Note

You can use brackets with comparison and logical operators. For example: not (a and b).

Easy example

a = 10
b = 15

if a == b:
    print('The numbers are the same')
else:
    print('The numbers are different')
Show/Hide Output
The numbers are different

Examples

Example 1 - Printing the result of a comparison

a = 20
b = 20
print(a == b)
Show/Hide Output
True

Example 2 - Saving the result of a comparison to a variable

a = 20
b = 15
same = a == b
print(same)
Show/Hide Output
False

Example 3 - Using the result of a comparison in an IF statement

a = 20
b = 15

if a > b:
    print('a is bigger than b')
else:
    print('a is smaller than, or the same size as b')
Show/Hide Output
a is bigger than b

Example 4 - Using Boolean operators in an IF statement

level = 4
livesRemaining = 3

if livesRemaining > 0 and level <= 10:
    print('Let\'s play')
Show/Hide Output
Let's play

Example 5 - Using comparison operators in a while statement

This program will print the current level and add one to the current level each time it loops.

level = 1

while level <= 5:
    print('Current level: ' + level)
    level = level + 1
Show/Hide Output
Current level: 1
Current level: 2
Current level: 3
Current level: 4
Current level: 5

Example 6 - Using a NOT statement

gameOver = False

if not gameOver:
    print('Play Game')
else:
    print('Game over')
Show/Hide Output
Play Game

Note

This could be written as if gameOver == False but it is better written as above.

Example 7 - Multiple logical operators

gameOver = False
currentScore = 120
level = 7

if currentScore > 100 and level >= 5 and not gameOver:
    print('You\'re doing really well')
else:
    print('You must keep trying')
Show/Hide Output
You're doing really well

Key points

Warning

== is used for comparisons and = is used for assignment. So if a = b: will not work, but this mistake can lead to an assignment happening when you actually want a comparison.