Comparison Operators in Python


TL ; DR:






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.


Introduction

Comparison operators are fundamental in programming, allowing us to make decisions based on the comparison of values. They are essential in control flow statements like if statements, loops, and more. Understanding how to use these operators effectively can help you write more dynamic and responsive code.

Understanding the Basics

Comparison operators compare two values and return a Boolean value: True or False. Here are the basic comparison operators in Python:

For example:

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

Main Concepts

Comparison operators are often used within if statements to control the flow of a program. For instance:

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

In this example, the program checks if age is less than 15. If it is, it prints "You are not allowed." Otherwise, it prints "Have fun!"

Examples and Use Cases

Let's look at some more examples:

a = 10
b = 15

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

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

In this code, the first condition a == b evaluates to False, so nothing is printed. The second condition a < b evaluates to True, so "a is less than b" is printed.

Common Pitfalls and Best Practices

One common mistake is using a single equal sign = instead of a double equal sign == for comparison. The single equal sign is used for assignment, not comparison. Always use == when comparing values.

Best practices include writing clear and concise conditions and avoiding overly complex expressions. Break down complex conditions into simpler parts if necessary.

Advanced Techniques

Advanced comparison techniques include chaining multiple comparison operators and using logical operators like and, or, and not to combine multiple conditions.

a = 10
b = 15
c = 20

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

In this example, both conditions a < b and b < c must be true for the message to be printed.

Code Implementation

Here is a more comprehensive example demonstrating the use of comparison operators:

# Define variables
age = 18
height = 160

# Check if age is greater than or equal to 18
if age >= 18:
    print("You are an adult.")
else:
    print("You are a minor.")

# Check if height is less than 150
if height < 150:
    print("You are short.")
else:
    print("You are tall.")

This code checks if a person is an adult based on their age and if they are tall or short based on their height.

Debugging and Testing

When debugging code involving comparison operators, print the values being compared to ensure they are what you expect. Use assertions to test your functions:

def is_adult(age):
    return age >= 18

# Test cases
assert is_adult(20) == True
assert is_adult(17) == False

These assertions will raise an error if the function is_adult does not return the expected result.

Thinking and Problem-Solving Tips

When solving problems involving comparison operators, break down the problem into smaller parts. Write out the conditions you need to check and test each one individually. Practice with different scenarios to become more comfortable with these operators.

Conclusion

Mastering comparison operators is crucial for making decisions in your code. They are used in various control flow statements and are essential for writing dynamic and responsive programs. Practice using these operators in different contexts to improve your understanding and proficiency.

Additional Resources