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

If you type only the variable, it will round the number to the nearest whole value.

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