Integer Handling

Integer Handling


Number handling is similar to string handling except it is the manipulation of whole or decimal numbers. Before manipulating number values the variable must be converted to a string:

screenshot-2016-10-22-at-7-25-27-pm


Selecting Specific Digits


You can select a specific digit in the same manner as when selecting characters in a string. Remember that Python starts at zero:

screenshot-2016-10-22-at-7-29-06-pm

Writing int on the third line allows the firstdigit variable to be used as an integer in case you wanted to add it to another digit for example.

Practice Task 1

Shortening numbers


Just like a string, you can shorten a variable to only display a certain length (either to print as below or to overwrite the original variable):

screenshot-2016-10-22-at-7-40-28-pm

The above code would start at the second digit and print up to the fourth digit:

screenshot-2016-10-22-at-7-50-16-pm

Practice Task 2

 

Reversing a Number

Again, reversing a number is the same as reversing a string. I am not using the number for any calculations so I have not even used int(input() and so it is entered as a string automatically:

screenshot-2016-10-22-at-7-57-20-pm

screenshot-2016-10-22-at-8-00-00-pm

Practice Task 3

Rounding Numbers


Use the round() command with your number variable inside to round up or down to the nearest whole number:

screenshot-2016-10-22-at-8-20-36-pmscreenshot-2016-10-22-at-8-20-45-pm


Other Handling Techniques


Once you have inputted an integer remember to convert it to a string before you try other handling methods such as .startswith(). Also you should consider whether to apply the int(input() command to a number if you will not be using it as one (if you are not calculating using it for example).


< Back to Section Nine