Applying Comparison Operators in Python
Conditional Statements
One of the most common use cases for comparison operators in Python is within conditional statements, such as if-else
and if-elif-else
statements. These statements allow you to execute different blocks of code based on the result of the comparison.
## Example: Checking if a number is positive or negative
num = -5
if num > 0:
print("The number is positive.")
else:
print("The number is negative or zero.")
Loops
Comparison operators are also used in loop conditions to control the number of iterations or to exit a loop based on a certain condition.
## Example: Counting up to 5
count = 0
while count < 5:
print(count)
count += 1
Sorting and Filtering
Comparison operators can be used to sort and filter data in Python. For example, you can use the sorted()
function with a custom key function that utilizes comparison operators to sort a list of objects.
## Example: Sorting a list of people by age
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return f"{self.name} ({self.age})"
people = [
Person("Alice", 25),
Person("Bob", 30),
Person("Charlie", 20)
]
sorted_people = sorted(people, key=lambda p: p.age)
print(sorted_people) ## Output: ['Charlie (20)', 'Alice (25)', 'Bob (30)']
Logical Operators
Comparison operators can be combined with logical operators, such as and
, or
, and not
, to create more complex logical expressions.
## Example: Checking if a number is between 10 and 20
num = 15
if 10 <= num <= 20:
print("The number is between 10 and 20.")
else:
print("The number is not between 10 and 20.")
By understanding how to apply comparison operators in various programming constructs, you can write more dynamic and flexible Python code that can make decisions based on the relationships between values.