Compare Different Numeric Types
In this step, you will explore how the less than operator (<) works when comparing different numeric types in Python, such as integers and floating-point numbers.
Python supports various numeric types, including integers (int) and floating-point numbers (float). Integers are whole numbers without any decimal part, while floating-point numbers have a decimal part.
Let's create a new Python file named compare_types.py in the ~/project directory using the VS Code editor.
## ~/project/compare_types.py
integer_num = 10
float_num = 10.5
result = integer_num < float_num
print(result)
In this code, we have an integer variable integer_num with a value of 10 and a floating-point variable float_num with a value of 10.5. We then use the less than operator to compare these two variables.
Run the script using the following command in the terminal:
python compare_types.py
The output should be:
True
This is because the integer 10 is less than the floating-point number 10.5.
Now, let's try comparing an integer with a floating-point number that has the same whole number part:
## ~/project/compare_types.py
integer_num = 10
float_num = 10.0
result = integer_num < float_num
print(result)
Modify the compare_types.py file with the above content. Run the script again:
python compare_types.py
The output should be:
False
Even though the whole number part is the same, the integer 10 is not less than the floating-point number 10.0. They are considered equal in value, but the less than operator only returns True if the left-hand side is strictly less than the right-hand side.
Let's consider another example:
## ~/project/compare_types.py
integer_num = 5
float_num = 2.5
result = integer_num < float_num
print(result)
Modify the compare_types.py file with the above content. Run the script again:
python compare_types.py
The output should be:
False
In this case, the integer 5 is greater than the floating-point number 2.5, so the result is False.