How to Check if Two Variables Have the Same Value in Python?

Estimated read time 2 min read

To check if two variables have the same value in Python, you can use the == operator or the is operator. Here’s how you can use both operators:

  1. Using the == operator:
variable1 = 10
variable2 = 10

if variable1 == variable2:
    print("variable1 and variable2 have the same value.")
else:
    print("variable1 and variable2 do not have the same value.")

In this example, the if statement compares the values of variable1 and variable2 using the == operator. If the values are equal, the message “variable1 and variable2 have the same value” is printed. Otherwise, the message “variable1 and variable2 do not have the same value” is printed.

  1. Using the is operator:
variable1 = 10
variable2 = 10

if variable1 is variable2:
    print("variable1 and variable2 have the same value.")
else:
    print("variable1 and variable2 do not have the same value.")

In this example, the if statement uses the is operator to check if variable1 and variable2 refer to the same object in memory. In this case, since variable1 and variable2 are both integers with the same value, they will refer to the same object, and the message “variable1 and variable2 have the same value” will be printed. If the variables were mutable objects (e.g., lists, dictionaries) or had different identities, the is operator may not yield the expected result.

Generally, for comparing the values of variables, it is recommended to use the == operator. The is operator is more appropriate for checking if two variables refer to the same object in memory.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply