Now that we know how to work with numbers, including performing mathematical operations, let's learn how to format them better for display.
Open lab3.py from Project 2 - Temp Converter
One of the most common things you will need to do is round a number to a fixed amount of decimal places.
For this, we can use the round() function. Notice how you can specify the number of decimal places, or just round to an integer.
You may have a large number which would be more readable with commas as thousands separators.
Here we just use an f-string as normal, but after the variable place a colon and comma. Like this :,
You may have a very large or very small number which would be better presented with scientific notation.
Here we just use an f-string as normal, but after the variable place a colon, the number of significant figures and then 'e'. Like this :.2e
This is just the tip of the iceberg. There is a lot you can do with f-strings to format numbers (and other data types).
Here are just a couple of more examples before you attempt the lab.
Complete the following requirements:
Ask the user for a decimal number and store it in a variable 'num1', converting to a float
Round the number to 2 decimal places using the round function
Define a large integer
Print the large integer with commas as thousands separators using f-strings
Define a small floating-point number
Print the number in scientific notation using f-strings
Define a small integer
Print the number with leading zeros using f-strings
Press Ctrl + F5 to run the program or open a terminal and type python lab3.py
It should run without errors and you should see something like on the right:
Example:
Please enter a decimal number: 7.4398
Rounded to 2 decimal places: 7.44
Large Number: 1,234,567,890
Small Number: 1.23e-04
Leading Zeros: 00042
You should now know how to format numbers in a variety of ways in Python.
Let's wrap up this lab by pushing our code to GitHub:
Enter a commit message. E.g. "Lab 3 complete"
Press Commit to main
Press Push origin