How to compare two variables in an if statement using Python?

You can compare two variables in an if statement using comparison operators. Python provides several operators like == for value equality and is for identity comparison.

Using == Operator for Value Comparison

The == operator compares the values of two variables ?

a = 10
b = 15
if a == b:
    print("Equal")
else:
    print("Not equal")

The output of the above code is ?

Not equal

Using is Operator for Identity Comparison

The is operator checks if two variables point to the same object in memory ?

a = "Hello"
b = a
if a is b:
    print("Equal")
else:
    print("Not equal")

The output of the above code is ?

Equal

Other Comparison Operators

Python provides additional comparison operators for different conditions ?

x = 10
y = 20

# Greater than
if x > y:
    print(f"{x} is greater than {y}")
else:
    print(f"{x} is not greater than {y}")

# Less than or equal
if x <= y:
    print(f"{x} is less than or equal to {y}")

# Not equal
if x != y:
    print(f"{x} is not equal to {y}")

The output of the above code is ?

10 is not greater than 20
10 is less than or equal to 20
10 is not equal to 20

Key Differences

Operator Purpose Example
== Compares values [1, 2] == [1, 2] returns True
is Compares object identity [1, 2] is [1, 2] returns False
!= Not equal to 10 != 20 returns True

Conclusion

Use == to compare values and is to check if variables reference the same object. Choose the appropriate comparison operator based on your specific needs.

Updated on: 2026-03-24T20:36:51+05:30

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements