Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to compare numbers in Python?
You can use relational operators in Python to compare numbers (both float and int). These operators compare the values on either side of them and decide the relation among them.
Comparison Operators
Python provides six main comparison operators for comparing numbers ?
| Operator | Description | Example (a=10, b=20) | Result |
|---|---|---|---|
== |
Equal to | (a == b) |
False |
!= |
Not equal to | (a != b) |
True |
> |
Greater than | (a > b) |
False |
< |
Less than | (a < b) |
True |
>= |
Greater than or equal to | (a >= b) |
False |
<= |
Less than or equal to | (a <= b) |
True |
Example
Here's how you can use comparison operators in practice ?
a = 10 b = 20 print(a == b) # Equal to print(a != b) # Not equal to print(a > b) # Greater than print(a < b) # Less than print(a >= b) # Greater than or equal to print(a <= b) # Less than or equal to
False True False True False True
Comparing Different Number Types
Python can compare integers and floating-point numbers seamlessly ?
x = 5 y = 5.0 z = 5.5 print(x == y) # Integer vs Float print(x < z) # Integer vs Float print(y < z) # Float vs Float
True True True
Chaining Comparisons
Python allows you to chain multiple comparisons together ?
num = 15 # Check if num is between 10 and 20 print(10 < num < 20) # Multiple conditions print(5 < num <= 15) print(num == 15 != 10)
True True True
Conclusion
Python's comparison operators (==, !=, >, <, >=, <=) work seamlessly with both integers and floats. You can also chain multiple comparisons for more complex conditions, making your code more readable and efficient.
Advertisements
