Find Last Digit in Python

In the previous article we have gone through the sum of n digits problem, we continue in this article with a look at another common problem which is finding out the last digit. Suppose a user enters the number 234, it would return 4. If a user entered 1000 it would return a zero. A single digit returns the same number. So let us look at the how to implement a program to Find Last Digit in Python.

Implementation of Finding out the Last Digit in Python

In order to return the last digit we will utilize the % modulus operator

x= int (input("Enter x:"))
ld= x % 10
print("Last Digit is", ld)
Enter x:234
Last Digit is 4

While this approach works it is only suitable for numbers greater than or equal to 0. There is a solution logic to be followed when dealing with negative numbers

x=int(input("Enter x:"))
ld=abs(x) % 10
print("Last Digit is", ld)
Enter x:-121
Last Digit is 1

The program is able to work even with negative numbers as it utilizes the abs( ) absolute value function to return the absolute value of the specified number. Hence we are able to return the correct positive or negative last digit value.

Leave a Comment