
Practice: Mixing Ints and Floats
Working with integer and floating-point numbers together.
Mixing and Converting Between Integers and Floating-Point Numbers
In Python, you can convert an integer value to a float value by using the built-in float( ... ) function:
float(12)
- Will convert the integer value
12into the float value12.0and return it.
You can also convert a float value into an integer value by using the int( ... ) function:
int(12.0)
- Will convert the float value
12.0into the integer value12and return it.
One thing to keep in mind when converting float values into integers is that the new integer will drop any fractional part.
For example:
int(365.26)
- Will convert the float value
365.26into the integer value365and return it. This means the.26value is lost.
Practice: Number Type Conversion
With the above information about integer and float values in mind, complete the following steps.
- Define a variable named
months_as_float, and assign it7.28. - Print the value contained in the
months_as_floatvariable. - Define a variable named
months_as_int, and assign it the value ofmonths_as_floatconverted to an integer. - Print the value contained in the
months_as_intvariable. - Define a variable named
months_as_float_restored, and assign it the value ofmonths_as_intconverted to a float. - Print the value contained in the
months_as_float_restoredvariable.
HINT*: Click here for a hint
You should see the following:
>7.28 7 7.0
Note that integers don't store decimal information, so months_as_float_restored shouldn't have the original decimal value that months_as_float has.
SOLUTION*: Click here for an example solution
months_as_float = 7.28
print(months_as_float)
> 7.28
months_as_int = int(months_as_float)
print(months_as_int)
> 7
months_as_float_restored = float(months_as_int)
print(months_as_float_restored)
> 7.0
When you have completed the above, you are ready to move on to the next exercise!