top of page
top

Python 9b - Number Handling

noun-text-4214022-FFFFFF.png

Rounding Numbers

The round() command is used to round a value to a certain number of decimal places.

​

Type your variable into the round command brackets, add a comma and state the number of decimal places to round to.

py191.PNG
py192.PNG

Fixed Decimal Places (Currency)

The round function will remove any trailing 0s, for example 30.1032 will become 30.1 even if you specified to round to 2 decimal places.

​

Instead, you can use an f -string and write :.2f after a bracketed variable to use exactly 2 decimal places. The number can be changed from 2.

books = int(input("How many books would you like to buy? "))
total = books * 3.99

​

print(f"The total is £{total:.2f} - Thanks for your order!")

How many books would you like to buy? 10
The total is £39.90 - Thanks for your order!

How many books would you like to buy? 100
The total is £399.00 - Thanks for your order!

Practice Task 1

Ask the user to enter any large number.

​

Ask the user to enter another large number.

​

Divide the two numbers and print the answer to 3 decimal places.

Example solution:

py193.PNG

Using Numbers as Strings

The following techniques all require the integer to be converted into a string first using the str command.

​

Just like a string, you can shorten a variable to only display a certain length.

 

Remember that Python starts at zero.

py194.PNG
py195.PNG

You can select a specific digit in the same manner as when selecting characters in a string.

py196.PNG
py197.PNG

If you want to use your variable as an integer again later you would need to convert it from a string to an integer using the int command.

Again, reversing a number is the same as reversing a string.

py198.PNG
py199.PNG

You can also use other string handling methods such as .startswith() or .endswith()

Practice Task 2

Ask the user to enter a 10 digit number.

​

Select the 2nd and 8th digits and add them together.

​

Print the total.

Example solution:

py200.PNG
bottom of page