Start learning free

LESSON 74 OF 410 · CONDITIONAL STATEMENTS

Comparison Operators in Python

Lesson

TL ; DR:

  • When writing if statements, we usually compare two values using comparison operators:

    age = 10
    if age < 15:
        print("You are not allowed.")
    else:
        print("Have fun!")
    



Full lesson:

When writing if statements, we usually compare two values using one or more comparison operators:

Operator Name Examples
== Equal  x == 5,  x == y
!= Not equal  x != 3,  x != y
> Greater than  x > 5,  x > y
< Less than  x < 8,  x < y
>= Greater than or equal to  x >= 4,  x >= y
<= Less than or equal to  x <= 3,   x <= y

For example:

10 == 10 # Evaluates to True
3 < 2 # Evaluates to False
15 >= 15 # Evaluates to True
17 != 12 # Evaluates to True

We usually use these operators with variables:

a = 10
b = 15

if a == b:
    print("a is equal to b")

if a < b:
    print("a is less than b")

The first condition is not satisfied since 10 == 15 evaluates to False.

The second condition is satisfied since 10 < 15 evaluates to True.

The code above prints "a is less than b".


Assignment
Follow the Coding Tutorial and let's play with comparison operators.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 3
    Ctrl + Enter to check