Welcome to the Python Comparison Operators tutorial! In this lesson, you'll learn about the essential comparison operators that help you make decisions in your Python code and compare values. Let's dive in! 🐠
Comparison operators are used to evaluate if a certain relationship exists between two values. They help you decide which branch of your code to execute and make your programs more dynamic.
Here are the six basic comparison operators in Python:
==: Equal to!=: Not equal to>: Greater than<: Less than>=: Greater than or equal to<=: Less than or equal tox = 10
y = 20
# Check if x is equal to y
if x == y:
print("x is equal to y")
# Check if x is not equal to y
if x != y:
print("x is not equal to y")What will the output be if we run the above code?
The ordered comparison operators (>, <, >=, <=) allow you to check if a value is greater, less, or equal to another.
x = 10
y = 20
# Check if x is less than y
if x < y:
print("x is less than y")
# Check if y is greater than x
if y > x:
print("y is greater than x")What will the output be if we run the above code?
While basic comparison operators are enough for most cases, Python offers some advanced comparison operators as well:
is: Checks if the variables point to the same object (object identity)is not: Checks if the variables do not point to the same object>= and <= with strings: Compares lexicographically (alphabetically for strings, ASCII for numbers)x = [1, 2, 3]
y = [1, 2, 3]
# Check if x and y point to the same object
if x is y:
print("x and y point to the same object")
# Check if x and y do not point to the same object
if x is not y:
print("x and y do not point to the same object")
# Check if "apple" is greater than "banana" lexicographically
if "apple" > "banana":
print("apple is greater than banana")What will the output be if we run the above code?
Now you have a solid understanding of Python's comparison operators and can use them to make your code more dynamic and powerful. Practice using these operators in your own projects and keep learning!
Want to learn more about Python? Check out our other tutorials at CodeYourCraft. 🐍 Happy coding! 🎉