Is there a way to get the last digit of a number. I am trying to find variables that end with "1" like 1,11,21,31,41,etc..
If I use a text variable I can simply put
print number[:-1]
but it works for variables with text(like "hello) but not with numbers. With numbers I get this error:
TypeError: 'int' object is not subscriptable
I am trying to see if there's a better way to deal with numbers this way. I know a solution is to convert to a string and then do the above command but I'm trying to see if there's another way I have missed.
Thanks so much in advance...
To find last digit of a number, we use modulo operator %. When modulo divided by 10 returns its last digit. To finding first digit of a number is little expensive than last digit. To find first digit of a number we divide the given number by 10 until number is greater than 10.
∴ The Last digit of the number 13457194323 is 3.
Therefore, the last digit of 7355 is 3 .
Remainder when dividing by 10, as in
numericVariable % 10
This only works for positive numbers. -12%10 yields 8
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With