Kahibaro
Discord Login Register

Comparison operators

Comparison Operators

In Python, comparison operators let you compare values and get a Boolean result: either True or False. You typically use them in if, elif, and while conditions.

This chapter focuses on the comparison operators themselves: what they are, how they behave with different data types, and common pitfalls.

The Comparison Operators in Python

Here are the main comparison operators:

They always evaluate to a Boolean value (True or False).

x = 5
y = 10
print(x == y)   # False, because 5 is not equal to 10
print(x != y)   # True, because 5 is not equal to 10
print(x < y)    # True, 5 is less than 10
print(x >= 5)   # True, 5 is greater than or equal to 5

Equality vs Assignment: `==` vs `=`

A very common beginner confusion:

age = 18        # assignment: put 18 into the variable age
print(age == 18)  # comparison: is age equal to 18? -> True

Using = inside a condition is a syntax error:

# This will cause an error:
if age = 18:
    print("You are 18")

Python forces you to use == for comparisons so you don’t accidentally assign instead of compare.

Comparing Numbers

You can compare integers and floats directly:

a = 3
b = 4.0
print(a < b)     # True
print(a == b)    # False, 3 is not equal to 4.0
print(3 == 3.0)  # True: Python treats them as equal in value

Comparison operators work as you would expect from math:

Be careful with floats and equality due to rounding, especially after calculations:

result = 0.1 + 0.2
print(result)        # Might print 0.30000000000000004
print(result == 0.3) # Often False

For now, just remember: direct equality on floats can be unreliable after arithmetic.

Comparing Strings

Strings can also be compared.

String equality and inequality

Two strings are equal if they have exactly the same characters in the same order and with the same case:

name = "Alice"
print(name == "Alice")  # True
print(name == "alice")  # False, different case
print(name != "Bob")    # True

Spaces and punctuation matter:

print("hello" == "hello ")  # False, extra space at the end

String ordering (alphabetical comparisons)

<, <=, >, >= also work on strings. Python compares strings lexicographically (like dictionary order), using the Unicode code points of characters.

Basic rules to keep in mind:

Examples:

print("apple" < "banana")    # True
print("hello" > "hi")        # False ("hello" is smaller than "hi")
print("Cat" < "dog")         # True (uppercase C vs lowercase d)
print("Zoo" < "apple")       # True or False? Let's see:
                             # "Z" (90) vs "a" (97) -> True, "Z" < "a"

For user-facing comparisons (like sorting names), these details matter, but for simple condition checks, you usually just do equality checks like name == "Alice".

Comparing Booleans

Booleans themselves (True, False) can be compared, but you rarely need to.

In Python, True is treated as 1 and False as 0 when compared numerically:

print(True == 1)   # True
print(False == 0)  # True
print(True > False) # True, because 1 > 0

This can be surprising; try not to rely on it in beginner code. Prefer explicit comparisons like x == True or better, just if x: (covered elsewhere).

Comparing Different Types

In modern Python, most comparisons between unrelated types are not allowed, especially ordering comparisons. For example, you cannot meaningfully ask if a string is “less than” a number.

This is valid:

print(5 == "5")      # False, number vs string

But this is an error:

# TypeError:
print(5 < "10")      # Cannot compare int and str

Some type combinations work (like int and float), but as a beginner, assume you should compare values of the same or compatible types.

Chained Comparisons

Python allows you to chain comparisons in a mathematical style:

Instead of writing:

x = 5
print(2 < x and x < 10)

You can write:

x = 5
print(2 < x < 10)   # True

This is equivalent to:

$$
(2 < x) \land (x < 10)
$$

More examples:

age = 20
print(18 <= age <= 65)   # Is age between 18 and 65 inclusive?
print(0 <= age < 120)    # Common pattern for ranges

Chaining keeps code readable and matches how you write inequalities in math.

Using Comparisons in Conditions

Comparison expressions are most often used directly inside if, elif, and while:

temperature = 30
if temperature > 25:
    print("It's warm outside")
if temperature == 0:
    print("It's freezing")

You can combine multiple comparisons with logical operators like and and or (covered in another section):

age = 17
if age >= 13 and age <= 19:
    print("You are a teenager")

Common Beginner Mistakes with Comparisons

1. Using `=` instead of `==`

We already saw this, but it’s so common it’s worth repeating:

# Wrong:
# if age = 18:  # SyntaxError
# Right:
if age == 18:
    print("You are 18")

2. Comparing the wrong types (e.g. string vs number)

Input from users is usually a string. If you compare it directly to a number, it will always be False:

age_input = input("Enter your age: ")  # age_input is a string
print(age_input == 18)      # False, string vs int
print(age_input == "18")    # True if user typed 18

If you want numeric comparison, you must convert the input to a number (covered in the input section of the course).

3. Expecting case-insensitive comparisons

"Alice" == "alice" is False. If you want a case-insensitive check, you must normalize the case first:

name = input("Enter your name: ")
if name.lower() == "alice":
    print("Hello, Alice!")

4. Confusing `==` with `is`

is checks whether two variables refer to the same object in memory, not whether they have the same value. For value comparison, use ==.

For beginners, a simple rule: always use == to compare values, not is.

a = 1000
b = 1000
print(a == b)  # True, values are equal
print(a is b)  # Might be False, different objects

Practice Ideas

Try these small exercises to get comfortable with comparison operators:

  1. Write a program that asks for the user’s age and prints:
    • "You are a minor" if age < 18
    • "You are an adult" if age >= 18
  2. Ask the user for a password (as text) and check if it equals "secret123". Print a different message for correct vs incorrect password.
  3. Ask the user for a number and check:
    • if it is positive, negative, or zero
    • if it is between 1 and 10 (inclusive) using a chained comparison.
  4. Use a comparison with strings to check if a user’s name comes before "M" in alphabetical order.

These will help you see how comparison operators behave with numbers and strings in real conditions.

Views: 18

Comments

Please login to add a comment.

Don't have an account? Register now!