Glossary
HTML
CSS
JavaScript
Python

PYTHON

Python Equal: The Equality Operator in Python

The Python equality operator (==) checks if two variables or values are equal. The result of the evaluation is either True or False. The equality operator returns True if the values are equal. If the values aren't equal, the comparison returns False.

How to Use the Equality Operator in Python

The syntax for using the equality operator is straightforward:

Python

# Checking if two values are equal
result = (a == b)
print(result)
  • ==: The symbol for the equality operator.
  • a, b: The variables or values to compare.

When to Use the Equality Operator

The equality operator is helpful in various scenarios, from conditional logic to data validation. == is great for determining if a variable holds a certain value or if two variables hold the same value.

Examples of the Equality Operator in Python

User Input Validation

The equality operator is ideal for validating user inputs against expected values, like in login processes:

Python

entered_password = input("Enter your password: ")
if entered_password == "correct_password":
    print("Access granted.")
else:
    print("Access denied.")

Conditional Logic in Games

In game development, the equality operator can determine game states or player actions. As an example, consider checking if a player has reached a certain score:

Python

player_score = 100
if player_score == 100:
    print("Congratulations, you've reached the high score!")

Data Filtering

The equality operator is popular in data processing for filtering or grouping data based on specific criteria. For instance, == can help find a certain item in a list:

Python

items = ["apple", "banana", "cherry"]
for item in items:
    if item == "banana":
        print("Banana found!")

Function Return Value Checks

Functions often return values. The equality operator helps in evaluating return values to make decisions based on the outcome of function calls:

Python

def check_prime(number):
    # Assume there's logic here to check for prime
    return True  # Simplification for example

if check_prime(7) == True:
    print("7 is a prime number.")

Learn More About the Equality Operator in Python

Python Not Equal Operator

Python offers a direct way to express inequality. The not equal operator (!=) is essential for checking if two values aren't the same. Not equal is particularly useful in situations where an action is only necessary when values differ. For example, in a game, you might want to check if the current score is not equal to the high score to update it:

Python

current_score = 95
high_score = 100

if current_score != high_score:
    print("New high score!")
else:
    print("Try again to beat the high score.")

Comparing Different Data Types with the Equality Operator

The equal to operator works well when comparing values of the same data type. When using the == operator to compare values of different data types in Python, the result is usually False. Python comparison operators not only consider the value but also the type of the objects.

Python

int_number = 10
string_number = "10"

print(int_number == string_number)  # Outputs: False
print(int_number == int(string_number))  # Outputs: True

At first, the comparison will evaluate to False because comparing string and integer values can't be equal. However, after converting the string to an integer, the comparison will evaluate to True. Notable exceptions to this rule are types that are implicitly convertible to each other, like integers and floats. For example:

Python

if 1 == 1.0:
		print("True, because Python considers 1 and 1.0 equal in value.")

Python considers an integer and a float as equal if their values are the same, despite the difference in data types.

Overriding Default Equality

In Python, by default, the equality operator compares objects by their identity (memory location). However, you can override the __eq__() function in your classes to define custom equality. Overriding default equality is particularly useful when you consider objects equal based on their attributes, not their identities:

Python

class User:
    def __init__(self, username, email):
        self.username = username
        self.email = email

    def __eq__(self, other):
        if isinstance(other, User):
            return self.username == other.username and self.email == other.email
        return NotImplemented

user1 = User("john_doe", "john@example.com")
user2 = User("john_doe", "john@example.com")

print(user1 == user2)  # Outputs: True

By overriding the __eq__() function, the equality operator on classes or objects.

Combining with Logical Operators

Combining the equality operator with boolean operators (and, or, and not) allows for constructing complex logical expressions. Such combinations can enhance the decision-making capabilities in your code. As an example, think of a login process. To maintain security, you might want to verify that both username and password match the expected values:

Python

username = "admin"
password = "secure123"

if username == "admin" and password == "secure123":
    print("Access granted.")
else:
    print("Access denied.")

And for situations requiring at least one condition to be True, the or operator is useful:

Python

day = "Saturday"

if day == "Saturday" or day == "Sunday":
    print("It's the weekend!")
else:
    print("Back to work.")

== vs. is in Python

In Python, == and is are valid operators in boolean expressions but serve different purposes. The == operator checks if the values of two objects are equal, focusing on the content or data they hold. The is operator checks for object identity, determining if two references point to the same object in memory.

The equality operator is ideal for comparing the values of two objects. When using ==, the memory location of the objects is irrelevant. Therefore, two different list objects with the same elements are equal using ==:

Python

list1 = [1, 2, 3]
list2 = [1, 2, 3]
print(list1 == list2)  # Outputs: True

The Python is operator is great when you want to know if two variables reference the same object. This is important in scenarios where the distinction between identical objects and those with the same content matters:

Python

list1 = [1, 2, 3]
list2 = list1
print(list1 is list2)  # Outputs: True
list3 = [1, 2, 3]
print(list1 is list3)  # Outputs: False

In this example, list1 and list2 reference the same list object, so list1 is list2 is True. However, list1 and list3 are different objects with the same content, making list1 is list3 False.

Learn to Code in Python for Free
Start learning now
To advance beyond this tutorial and learn Python by doing, try the interactive experience of Mimo. Whether you're starting from scratch or brushing up your coding skills, Mimo helps you take your coding journey above and beyond.

Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.

You can code, too.

© 2023 Mimo GmbH