To get the last digit of a number in Python:
- Access the string representation of the number.
- Get the last character of the string representation.
- Convert the character to an integer.
For example, let’s get the last digit of the number 162329:
n = 162329 # 1. Get the string representation num_str = repr(n) # 2. Access the last string of the digit string: last_digit_str = num_str[-1] # 3. Convert the last digit string to an integer: last_digit = int(last_digit_str) print(f"The last digit of {n} is {last_digit}")
Output:
The last digit of 162329 is 9
Shorthand Approach
You can also make the above code a bit shorter by combining steps 1-3 into a single expression:
n = 162329 last_digit = int(repr(n)[-1]) print(f"The last digit of {n} is {last_digit}")
The result:
The last digit of 162329 is 9
How to Get the Last Digit of a Decimal in Python
The same approach you learned earlier also works for decimal numbers.
To get the last digit of a decimal number, convert the number to a string, get the last character, and convert it back to an integer.
For example, let’s get the last decimal of a three-decimal approximation of Pi.
pi = 3.141 last_digit = int(repr(pi)[-1]) print(f"The last digit of {pi} is {last_digit}")
Output:
The last digit of 3.141 is 1