Python Arena
Step 2 of 5

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.")
Input
4
Output
Guess 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!")
Python stops with
  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.")
Input
Yes
Output
Do 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.

Your task

Challenge 1 of 3

Fill in the blank so the program unlocks only with the PIN 4321. If the user types 4321, the run looks like this:

PIN: 4321
Unlocked

Challenge 2

Write a program that asks for two whole numbers and tells which one is bigger, with one of these three messages:

  • The first number is bigger.
  • The second number is bigger.
  • The numbers are equal.

If the user types 5 and 8, the run looks like this:

First: 5
Second: 8
The second number is bigger.

Challenge 3

At the museum, a ticket costs 5 for visitors under 12 and 10 for everyone 12 or older. Write a program that asks for the visitor's age and prints the price. If the user types 12, the run looks like this:

Age: 12
Ticket: 10 euros

Make sure that a visitor who is exactly 12 pays 10.