Compare Integers and Floats
In this step, you will learn how to compare integers and floats using comparison operators in Python. Integers are whole numbers (e.g., 5, -3, 0), while floats are numbers with decimal points (e.g., 3.14, -2.5, 0.0). Python can compare these two data types seamlessly.
Let's create a new Python file named compare_int_float.py
in your ~/project
directory to explore this.
- Open VS Code.
- Create a new file named
compare_int_float.py
in the ~/project
directory.
- Add the following code to the
compare_int_float.py
file:
integer_value = 10
float_value = 10.0
print("integer_value == float_value:", integer_value == float_value)
print("integer_value > float_value:", integer_value > float_value)
print("integer_value < float_value:", integer_value < float_value)
integer_value_2 = 5
float_value_2 = 2.5
print("integer_value_2 > float_value_2:", integer_value_2 > float_value_2)
print("integer_value_2 < float_value_2:", integer_value_2 < float_value_2)
In this code, we are comparing integers and floats using the ==
, >
, and <
operators. The first set of comparisons checks if an integer value is equal to, greater than, or less than a float value with the same numerical value. The second set of comparisons checks if an integer is greater or less than a different float value.
Now, let's run the script:
- Open your terminal in VS Code.
- Execute the following command:
python compare_int_float.py
You should see the following output:
integer_value == float_value: True
integer_value > float_value: False
integer_value < float_value: False
integer_value_2 > float_value_2: True
integer_value_2 < float_value_2: False
The output shows that even though 10
and 10.0
are different data types, Python considers them equal in value. It also correctly compares 5
and 2.5
, showing that 5
is greater than 2.5
.