Introduction to Python Resources

Begin your free Python journey now,
at your own pace

check

Practice: Mixing Ints and Floats

check

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 12 into the float value 12.0 and 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.0 into the integer value 12 and 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.26 into the integer value 365 and return it. This means the .26 value is lost.

Practice: Number Type Conversion

With the above information about integer and float values in mind, complete the following steps.

  1. Define a variable named months_as_float, and assign it 7.28.
  2. Print the value contained in the months_as_float variable.
  3. Define a variable named months_as_int, and assign it the value of months_as_float converted to an integer.
  4. Print the value contained in the months_as_int variable.
  5. Define a variable named months_as_float_restored, and assign it the value of months_as_int converted to a float.
  6. Print the value contained in the months_as_float_restored variable.
HINT*: Click here for a hint
*Hints are best viewed after completing a task, or after spending some time and effort attempting it. In cases where a hint contains example output, it is important to understand why it is correct, as there may be many correct outputs.

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
*Example solutions are best viewed after completing a task and understanding the outcome. In most cases, there are multiple ways to complete a task, and the example solution is only one example.
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!