How to Compare Two Numbers in Python?

Estimated read time 3 min read

To compare two numbers in Python, you can use comparison operators. Here are the common comparison operators and examples of how to use them:

  1. Equal to (==): This operator checks if two numbers are equal.
a = 5
b = 7

if a == b:
    print("a is equal to b")
else:
    print("a is not equal to b")

In this example, a is not equal to b, so the output will be “a is not equal to b”.

  1. Not equal to (!=): This operator checks if two numbers are not equal.
a = 5
b = 7

if a != b:
    print("a is not equal to b")
else:
    print("a is equal to b")

In this example, a is not equal to b, so the output will be “a is not equal to b”.

  1. Greater than (>) and Greater than or equal to (>=): These operators compare if one number is greater than or greater than or equal to the other.
a = 5
b = 7

if a > b:
    print("a is greater than b")
else:
    print("a is not greater than b")

if a >= b:
    print("a is greater than or equal to b")
else:
    print("a is less than b")

In this example, a is not greater than b, so the first condition is not met and the output will be “a is not greater than b”. Also, a is not greater than or equal to b, so the second condition is not met and the output will be “a is less than b”.

  1. Less than (<) and Less than or equal to (<=): These operators compare if one number is less than or less than or equal to the other.
a = 5
b = 7

if a < b:
    print("a is less than b")
else:
    print("a is not less than b")

if a <= b:
    print("a is less than or equal to b")
else:
    print("a is greater than b")

In this example, a is less than b, so the first condition is met and the output will be “a is less than b”. Also, a is less than or equal to b, so the second condition is met and the output will be “a is less than or equal to b”.

These are the basic comparison operators that allow you to compare two numbers in Python. Choose the appropriate operator based on the specific comparison you want to perform.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply