Printing floats
Scientific notation is a powerful tool for representing numbers, but it can be confusing to handle when trying to print float values. However, we can use the f strings we learned about previously to make sure we get them printed properly every time by using a format specifier. For example, if we wanted to format a variable in an f string as a float, we can use the f
format specifier, such as: print(f"{some_variable:f}")
. It also takes an operation precision on the float format specifier, for example, print(f"{some_variable:.4f}")
would print four decimal places of precision.
This is a part of the course
“Data Types in Python”
Exercise instructions
- Print
float1
,float2
, andfloat3
notice where the jump to scientific notation occurs. - Print
float2
andfloat3
using the default float format specifier, and notice what happened tofloat3
. - Print
float3
with the float format specifier and a precision of7
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Print floats 1, 2, and 3
print(____)
print(____)
print(____)
# Print floats 2 and 3 using the f string formatter
print(f"{____}")
print(f"{____}")
# Print float 3 with a 7 f string precision
print(f"{____}")
This exercise is part of the course
Data Types in Python
Consolidate and extend your knowledge of Python data types such as lists, dictionaries, and tuples, leveraging them to solve Data Science problems.
Let's take a step away from dictionaries and look at some other common numeric and boolean data types along with sets.
Exercise 1: Numeric data typesExercise 2: Choosing when to use integers and floatsExercise 3: Printing floatsExercise 4: Division with integers and floatsExercise 5: Booleans - The logical data typeExercise 6: More than just true and falseExercise 7: ComparisonsExercise 8: Truthy, True, Falsey, and FalseExercise 9: Sets (unordered data with optimized logic operations)Exercise 10: Determining set differencesExercise 11: Finding all the data and the overlapping data between setsWhat is DataCamp?
Learn the data skills you need online at your own pace—from non-coding essentials to data science and machine learning.