Comparison operators
A condition usually compares two values. These are Python's comparison operators:
| Operator | Means | Example |
|---|---|---|
== |
equal to | a == b |
!= |
not equal to | a != b |
< |
less than | a < b |
<= |
less than or equal to | a <= b |
> |
greater than | a > b |
>= |
greater than or equal to | a >= b |
The difference between < and <= matters at the edge: 18 < 18 is false, but 18 <= 18 is true.
A program can have several if statements one after another. This guessing game has three:
secret = 7
guess = int(input("Guess a number from 1 to 10: "))
if guess < secret:
print("Too small.")
if guess > secret:
print("Too big.")
if guess == secret:
print("Right! Well done.")
4Guess a number from 1 to 10: 4
Too small.Python checks each if on its own, in order. A number can't be smaller than 7, bigger than 7 and equal to 7 at the same time, so exactly one of the three messages is printed.
= is not ==
A single = stores a value in a variable. Two, ==, compare two values. Mixing them up is one of the most common mistakes, and in a condition Python catches it:
guess = 7
if guess = 7:
print("Right!")
File "main.py", line 2
if guess = 7:
^^^^^^^^^
SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?Python suggests == or :=. The second is a rarer operator that this course doesn't need: == is the one you want.
Comparing strings
== and != work for strings too. Two strings are equal only when they are exactly the same, character by character, capitals and spaces included:
answer = input("Do you like Python? ")
if answer == "yes":
print("Great!")
if answer != "yes":
print("Give it a few more weeks.")
YesDo you like Python? Yes
Give it a few more weeks.Yes with a capital Y is not the same string as yes. != is handy for doing something whenever a value is anything but one particular value.