KAHIBARO Bookshelves
Discord Login Register

6.1. 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:

  • Equal to: ==
  • Not equal to: !=
  • Greater than: >
  • Greater than or equal to: >=
  • Less than: <
  • Less than or equal to: <=

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:

  • = is the assignment operator (used to give a value to a variable).
  • == is the equality comparison operator (used to compare two values).
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:

  • $a < b$ means “$a$ is strictly less than $b$”
  • $a \le b$ means “$a$ is less than or equal to $b$”
  • $a > b$ means “$a$ is strictly greater than $b$”
  • $a \ge b$ means “$a$ is greater than or equal to $b$”

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:

  • "a" < "b" is True
  • "apple" < "banana" is True
  • If one is a prefix of the other, the shorter one is considered smaller:
    • "app" < "apple" is True
  • Uppercase letters come before lowercase letters in Unicode:
    • "A" < "a" is True

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.

  • True == True is True
  • True == False is False

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: 0

Comments

Please login to add a comment.

Don't have an account? Register now!

Where to Move

Move chapter:

  • ☰ 1. Chapter 1: What Is Programming?
    • ☰ 1.1. What is a computer program?
      • ☰ 1.2. What is Python?
        • ☰ 1.3. Where is Python used?
          • ☰ 1.4. How programming helps solve problems
            • ☰ 1.5. Your first Python program
            • ☰ 2. Chapter 2: Setting Up Python
              • ☰ 2.1. Installing Python (Windows / macOS / Linux)
                • ☰ 2.2. Using Python in the terminal
                  • ☰ 2.3. Using an IDE (IDLE / VS Code)
                    • ☰ 2.4. Running Python scripts
                      • ☰ 2.5. Python interactive mode
                      • ☰ 3. Chapter 3: Variables and Data Types
                        • ☰ 3.1. What is a variable?
                          • ☰ 3.2. Creating variables
                            • ☰ 3.3. Numbers
                              • ☰ 3.4. Test
                                • ☰ 3.5. Boolean values
                                  • ☰ 3.6. Type checking
                                  • ☰ 4. Chapter 4: Basic Operations
                                    • ☰ 4.1. Arithmetic operations
                                      • ☰ 4.2. Working with numbers
                                        • ☰ 4.3. String operations
                                          • ☰ 4.4. Combining text and variables
                                            • ☰ 4.5. Comments in Python
                                            • ☰ 5. Chapter 5: User Input and Output
                                              • ☰ 5.1. Getting input from the user
                                                • ☰ 5.2. Converting input to numbers
                                                  • ☰ 5.3. Formatting output
                                                    • ☰ 5.4. Writing interactive programs
                                                    • ☰ 6. Chapter 6: Conditions
                                                      • ☰ 6.1. Comparison operators
                                                        • ☰ 6.2. Logical operators
                                                          • ☰ 6.3. if, elif, else
                                                            • ☰ 6.4. Nested conditions
                                                              • ☰ 6.5. Common beginner mistakes
                                                              • ☰ 7. Chapter 7: Loops
                                                                • ☰ 7.1. Why loops are useful
                                                                  • ☰ 7.2. for loops
                                                                    • ☰ 7.3. while loops
                                                                      • ☰ 7.4. Loop counters
                                                                        • ☰ 7.5. break and continue
                                                                          • ☰ 7.6. Loop exercises
                                                                          • ☰ 8. Chapter 8: Data Collections
                                                                            • ☰ 8.1. Lists
                                                                              • ☰ 8.2. Tuples
                                                                                • ☰ 8.3. Dictionaries
                                                                                  • ☰ 8.4. Sets (basics)
                                                                                    • ☰ 8.5. Choosing the right data structure
                                                                                    • ☰ 9. Chapter 9: Functions
                                                                                      • ☰ 9.1. Why functions matter
                                                                                        • ☰ 9.2. Defining functions
                                                                                          • ☰ 9.3. Parameters and arguments
                                                                                            • ☰ 9.4. Return values
                                                                                              • ☰ 9.5. Scope (local vs global)
                                                                                                • ☰ 9.6. Reusing code
                                                                                                • ☰ 10. Chapter 10: Working with Files
                                                                                                  • ☰ 10.1. What is a file?
                                                                                                    • ☰ 10.2. Reading text files
                                                                                                      • ☰ 10.3. Writing and appending files
                                                                                                        • ☰ 10.4. File paths
                                                                                                          • ☰ 10.5. Simple file-based programs
                                                                                                          • ☰ 11. Chapter 11: Errors and Debugging
                                                                                                            • ☰ 11.1. Types of errors
                                                                                                              • ☰ 11.2. Reading error messages
                                                                                                                • ☰ 11.3. Common beginner errors
                                                                                                                  • ☰ 11.4. try and except
                                                                                                                    • ☰ 11.5. Debugging strategies
                                                                                                                    • ☰ 12. Chapter 12: Using Python Libraries
                                                                                                                      • ☰ 12.1. What is a library?
                                                                                                                        • ☰ 12.2. Importing modules
                                                                                                                          • ☰ 12.3. Standard libraries
                                                                                                                            • ☰ 12.3.1. math
                                                                                                                              • ☰ 12.3.2. random
                                                                                                                                • ☰ 12.3.3. datetime
                                                                                                                                • ☰ 12.4. Installing external libraries with pip
                                                                                                                                • ☰ 13. Chapter 13: Object-Oriented Programming
                                                                                                                                  • ☰ 13.1. What is object-oriented programming?
                                                                                                                                    • ☰ 13.2. Classes and objects
                                                                                                                                      • ☰ 13.3. The `__init__` method
                                                                                                                                        • ☰ 13.4. Attributes and methods
                                                                                                                                          • ☰ 13.5. Encapsulation
                                                                                                                                            • ☰ 13.6. Inheritance (basics)
                                                                                                                                              • ☰ 13.7. Simple OOP examples
                                                                                                                                              • ☰ 14. Chapter 14: Automation with Python
                                                                                                                                                • ☰ 14.1. What is automation?
                                                                                                                                                  • ☰ 14.2. Automating simple tasks
                                                                                                                                                    • ☰ 14.3. Working with files and folders
                                                                                                                                                      • ☰ 14.4. Automating text processing
                                                                                                                                                        • ☰ 14.5. Scheduling scripts
                                                                                                                                                          • ☰ 14.6. Practical automation examples
                                                                                                                                                          • ☰ 15. Chapter 15: Web Development with Python
                                                                                                                                                            • ☰ 15.1. How the web works (basic overview)
                                                                                                                                                              • ☰ 15.2. Introduction to Flask
                                                                                                                                                                • ☰ 15.3. Creating a simple web server
                                                                                                                                                                  • ☰ 15.4. Routing and templates
                                                                                                                                                                    • ☰ 15.5. Handling user input (forms)
                                                                                                                                                                      • ☰ 15.6. Very basic APIs
                                                                                                                                                                      • ☰ 16. Chapter 16: Data Science with Python
                                                                                                                                                                        • ☰ 16.1. What is data science?
                                                                                                                                                                          • ☰ 16.2. Working with data
                                                                                                                                                                            • ☰ 16.3. Introduction to NumPy
                                                                                                                                                                              • ☰ 16.4. Introduction to pandas
                                                                                                                                                                                • ☰ 16.5. Data visualization with matplotlib
                                                                                                                                                                                  • ☰ 16.6. Simple data analysis examples
                                                                                                                                                                                  • ☰ 17. Chapter 17: Mini Projects
                                                                                                                                                                                    • ☰ 17.1. Number guessing game
                                                                                                                                                                                      • ☰ 17.2. Simple calculator
                                                                                                                                                                                        • ☰ 17.3. To-do list
                                                                                                                                                                                          • ☰ 17.4. Password generator
                                                                                                                                                                                            • ☰ 17.5. Quiz application
                                                                                                                                                                                              • ☰ 17.6. Small web or data project
                                                                                                                                                                                              • ☰ 18. Chapter 18: Next Steps
                                                                                                                                                                                                • ☰ 18.1. How to practice Python
                                                                                                                                                                                                  • ☰ 18.2. Writing clean and readable code
                                                                                                                                                                                                    • ☰ 18.3. Choosing a specialization
                                                                                                                                                                                                      • ☰ 18.3.1. Web development
                                                                                                                                                                                                        • ☰ 18.3.2. Data science
                                                                                                                                                                                                          • ☰ 18.3.3. Automation
                                                                                                                                                                                                            • ☰ 18.3.4. Software development
                                                                                                                                                                                                            • ☰ 18.4. Learning resources and communities
                                                                                                                                                                                                            • ☰ 19. Appendix
                                                                                                                                                                                                              • ☰ 19.1. Python syntax cheat sheet
                                                                                                                                                                                                                • ☰ 19.2. Common errors and solutions
                                                                                                                                                                                                                  • ☰ 19.3. Glossary of terms