Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check last digit of number

Tags:

python

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...

like image 710
Lostsoul Avatar asked Mar 10 '11 02:03

Lostsoul


People also ask

How do you find the last digit of a number?

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.

What is the last digit of the number 13457 194323?

∴ The Last digit of the number 13457194323 is 3.

What is the last digit of 7 355?

Therefore, the last digit of 7355 is 3 .


2 Answers

Remainder when dividing by 10, as in

numericVariable % 10 

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

like image 131
Jim Garrison Avatar answered Oct 23 '22 11:10

Jim Garrison


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).

like image 24
Cameron Avatar answered Oct 23 '22 12:10

Cameron