Check the Numeric Type (Solution)
00:00 This is a fairly long description, but don’t get scared away. Some of it is just the expected output of the program that we’ll build here. We’ll start by getting two numbers from the user and storing them in Python variables while remembering to convert the provided values to floats.
00:26
Then we’ll calculate the difference and assign it to another variable. Let’s save our program and run it in the Python shell. I’ll type 1.5
as the first number, followed by .5
.
00:41
This should calculate the difference and put it into our diff
variable. As you can see, the variable contains a floating-point number because we’ve converted both inputs to floats. Now, each float has a convenient method you can use to test whether your number is an integer. In this case it is, but if we were to manually update the variables so that it contains a fractional value, such as 3.14
, then the method will return False
. Great.
01:13
Let’s use this method in our program. We’ll print the message using another f-string literal that says f"The difference between {num1} and {num2}
is an integer?"
then a space, and we’ll call the .is_integer()
method on the difference.
01:36
We can save and test our program. 1.5
and .5
. Let’s run it again. This time, I’ll enter numbers 1.5
and 1
.
01:50 The difference is not an integer, which is correct. Okay. That was the last exercise in this course. If you’ve come to this point, then congratulations. You did a terrific job.
![Avatar image for Bartosz Zaczyński](/cdn-cgi/image/width=500,height=500,fit=crop,gravity=auto,format=auto/https://files.realpython.com/media/coders_lab_2109368.259b1599fbee.jpg)
Bartosz Zaczyński RP Team on Feb. 10, 2025
@rombaut1977 Yes, you’re absolutely right. When you subtract 1.9 from 4.9 using Python floats, then you’ll get something like this:
>>> 4.9 - 1.9
3.0000000000000004
It’s almost correct and sufficient for most purposes, except for financial operations, which require utmost precision. In cases like this, you can use Python’s decimal.Decimal data type:
>>> from decimal import Decimal
>>> Decimal("4.9") - Decimal("1.9")
Decimal('3.0')
>>> float(Decimal("4.9") - Decimal("1.9"))
3.0
This type lets you take advantage of fixed-point arithmetic, which your hand-held calculator uses internally.
Become a Member to join the conversation.
rombaut1977 on Feb. 8, 2025
If you put in 4.9 - 1.9, the result is
False
? Is this due to the floating point error?