Python Get Last Digit of Int

Python Get Last Digit of Int | In this article, we will see how to get the last digit of an int in python. We will make use of various methods to find the last digit of an int. Let’s see an ordinary example first and then we can move forward and see different methods to do the same.

Python Get Last Digit of Int using the Modulus Operator

The modulus % operator can be used to find the remainder of a number and then return its last digit as the output. We will make use of this concept and see how to get the last digit of an int in python.

Example:
Find the last digit in the int 123

Code for Python get last digit of int 123:-

num = int(123)
last_digit = num % 10
print("The last digit in %d = %d" % (num, last_digit))

Output:-

The last digit in 123 = 3

We took the input int 123 and made use of the modulo. When it is divided by10, it returns the last digit of the number, in this case, it returned 3.

Let us see another example by taking input from the end-user,

num = int(input("Enter a number: "))
last_digit = num % 10
print("The last digit in %d = %d" % (num, last_digit))

Output:-

Enter a number: 452679
The last digit in 452679 = 9

Enter a number: 89568674165
The last digit in 89568674165 = 5

Python Get Last Digit of Int using Strings

Approach:-

1) The number’s string form can be viewed.
2) Have the string’s last character.
3) Convert character to an int.

num = 12345

# string representation
num_str = repr(num)

# make use of the last string of the digit string
last_digit_str = num_str[-1]

# convert the last digit string to an int
last_digit = int(last_digit_str)
print(f"Last digit = {last_digit}")

Output:-

Last digit = 5

In short, we retrieve the string, get the last character, and change it back to an integer. For user input, we can write the same code as:-

Python get last digit of int using Strings by taking input from the user

num = int(input("Enter a number: "))
num_str = repr(num)
last_digit_str = num_str[-1]
last_digit = int(last_digit_str)
print(f"Last digit = {last_digit}")

Output:-

Enter a number: 1023
Last digit = 3

Thus, we learned how to get the last digit of an int in python using two different methods. Both the methods are easy to understand and apply, we hope that you found them useful. Also see:- Find Shortest Word in List Python

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published.