Comparison operators (==, !=, >, <)

In Python, comparison operators are used to compare two values. They evaluate the relationship between the values and always return a Boolean result: either True or False.

Here are the primary comparison operators in Python, along with >= (greater than or equal to) and <= (less than or equal to), demonstrated through 10 practical examples:

1. Equal To (==) with Numbers

The == operator checks if the value on the left is exactly equal to the value on the right.

Python

score = 100
print(score == 100)  # Output: True
print(score == 50)   # Output: False

2. Equal To (==) with Strings

When comparing strings, == is case-sensitive. The characters must match perfectly.

Python

password = "Secret"
print(password == "Secret")  # Output: True
print(password == "secret")  # Output: False (lowercase 's')

3. Not Equal To (!=) with Numbers

The != operator is the opposite of ==. It returns True if the values are different.

Python

attempts = 3
print(attempts != 5)  # Output: True (3 is not equal to 5)

4. Not Equal To (!=) with Strings

You can use != to ensure a variable does not hold a specific text value.

Python

user_role = "guest"
print(user_role != "admin")  # Output: True

5. Greater Than (>)

Checks if the left value is strictly larger than the right value.

Python

temperature = 35
print(temperature > 30)  # Output: True
print(temperature > 40)  # Output: False

6. Less Than (<)

Checks if the left value is strictly smaller than the right value.

Python

items_in_cart = 4
print(items_in_cart < 10)  # Output: True

7. Greater Than or Equal To (>=)

Returns True if the left value is larger than or exactly equal to the right value.

Python

age = 18
print(age >= 18)  # Output: True (it is exactly 18)
print(age >= 21)  # Output: False

8. Less Than or Equal To (<=)

Returns True if the left value is smaller than or exactly equal to the right value.

Python

speed = 60
speed_limit = 60
print(speed <= speed_limit)  # Output: True

9. Comparing Different Data Types (Int and Float)

Python is smart enough to compare numerical values across different types, such as integers and floats, to see if they hold the same mathematical value.

Python

integer_value = 5
float_value = 5.0

print(integer_value == float_value)  # Output: True

10. Chained Comparisons

Python allows you to chain multiple comparison operators together to check if a value falls within a specific range.

Python

test_score = 85

# Checks if test_score is greater than 0 AND less than 100
print(0 < test_score < 100)  # Output: True

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *