
Concepts: Floats
Representing non-whole, very small, and very large numbers in Python with floating-point numbers.
Floating-Point Numbers in Python
Floats, or floating-point numbers, are numbers that can contain a decimal point. In Python, floats are differentiated from ints (integers) by including a decimal point when writing them out:
3.14
2.8
9.0
200.
Any number that doesn't include a decimal point is counted as an integer instead of a float. For example, 74 is an integer, while 74.0 is a floating-point number.
It is also worth pointing out that because integers and floats are different types in Python, using them together in calculations will result in a float value. For example:
-
When adding an integer value to a float value:
>35 + 5.0 40.0 -
When subtracting a float value from an integer value:
>27 - 2.0 25.0
Notice in both of the examples above that the calculations don't have a result with a decimal value, but because the calculations involved a float value, the result must be a float value.
Practice: Floats
Based on the above information, please complete the following steps:
- Define a variable named
gpaand assign it your most recent school grade-point-average (or make one up, if you don't remember), as a floating-point number with two decimal places. - Print the value contained in the
gpavariable. - Next, check the
typeof thegpavariable.
HINT*: Click here for a hint
You should see your grade-point-average output in the terminal, with up to two decimal places:
> 2.63
SOLUTION*: Click here for an example solution
gpa = 2.63
print(gpa)
2.63
type(gpa)
<class 'float'>
Even if all the decimal places of a floating-point number are 0, it's output should show at least one decimal place:
> 3.0
SOLUTION*: Click here for an example solution
gpa = 3.00
print(gpa)
3.0
type(gpa)
<class 'float'>
When you have completed the above, you are ready to move on to the next exercise!