How to check last digit of number

Remainder when dividing by 10, as in

numericVariable % 10

This only works for positive numbers. -12%10 yields 8


So you want to access the digits in a integer like elements in a list; easiest way I can think of is:

n = 56789
lastdigit = int(repr(n)[-1])
# >  9

Convert n into a string, accessing last element then use int constructor to convert back into integer.

For a Floating point number:

n = 179.123
fstr = repr(n)
signif_digits, fract_digits = fstr.split('.')
# >  ['179', '123']
signif_lastdigit = int(signif_digits[-1])
# >  9

Use the modulus operator with 10:

num = 11
if num % 10 == 1:
    print 'Whee!'

This gives the remainder when dividing by 10, which will always be the last digit (when the number is positive).

Tags:

Python