How to print the last digit of a number in Python
Learn how to print the last digit of a number in Python. Explore different methods, tips, real-world applications, and common error fixes.
.png)
You can easily get the last digit of a number in Python with a simple mathematical trick. The modulo operator, %, provides a straightforward way to handle this common programming task.
In this article, you'll learn different methods to print the last digit. We'll cover practical tips, real-world applications, and debugging advice to help you apply this skill confidently in your own projects.
Using the % operator
number = 12345
last_digit = number % 10
print(f"The last digit of {number} is: {last_digit}")--OUTPUT--The last digit of 12345 is: 5
The magic here is the modulo operator, %. It's a straightforward way to get the remainder of a division. When you divide any integer by 10, the remainder is always its last digit. This works because our number system is base-10.
So, 12345 % 10 effectively asks, "What's left over after dividing 12345 by 10?" The answer is 5. This technique is not only clean but also computationally efficient for isolating the final digit of any integer, whether it's positive or negative.
Basic methods for extracting the last digit
While the % operator is common, you can also get the last digit by converting the number to a string or using built-in functions like divmod().
Converting a number to a string
number = 9876
last_digit = int(str(number)[-1])
print(f"The last digit of {number} is: {last_digit}")--OUTPUT--The last digit of 9876 is: 6
Another way to grab the last digit is by treating the number as text. You first convert the integer into a string with the str() function. This turns a number like 9876 into the string "9876".
- Since strings are sequences, you can access individual characters.
- Using the index
[-1]fetches the last character of the string. - Finally, you convert that character back to an integer using
int().
This method is intuitive if you're comfortable with string manipulation, though it can be slightly less performant than the modulo operator for very large numbers.
Using the divmod() function
number = 54321
_, last_digit = divmod(number, 10)
print(f"The last digit of {number} is: {last_digit}")--OUTPUT--The last digit of 54321 is: 1
The divmod() function is a Python built-in that efficiently handles two tasks at once. It performs both integer division and a modulo operation, returning the results as a pair of numbers called a tuple.
- When you call
divmod(number, 10), it returns the quotient and the remainder. - You can unpack this tuple directly into variables. The underscore
_is a common placeholder for the quotient, which you don't need here. - This leaves the
last_digitvariable with the remainder—the final digit of the original number.
Using floor division and subtraction
number = 7890
last_digit = number - (number // 10) * 10
print(f"The last digit of {number} is: {last_digit}")--OUTPUT--The last digit of 7890 is: 0
This approach uses a bit of arithmetic to isolate the last digit. It works by creating a version of the number that ends in zero and then finding the difference.
- First, the floor division
number // 10effectively removes the last digit. For7890, this gives you789. - Next, multiplying that result by
10scales it back up to7890. - Finally, subtracting this from the original number (
7890 - 7890) leaves you with the remainder, which is the last digit.
Advanced techniques for handling digits
For more complex situations, such as dealing with negative values, very large numbers, or using regular expressions, you'll need to expand your toolkit beyond the simple operators.
Using regular expressions
import re
number = 24680
last_digit = int(re.search(r'(\d)$', str(number)).group(1))
print(f"The last digit of {number} is: {last_digit}")--OUTPUT--The last digit of 24680 is: 0
Regular expressions offer a powerful, though more complex, way to find the last digit. After converting the number to a string, the re.search() function hunts for a pattern. It's a bit like using a search command specifically for text structures.
- The pattern used here is
r'(\d)$'. The\dmatches any single digit. - The
$is an anchor that specifies the match must happen at the very end of the string. - Parentheses around
\dcreate a capturing group to isolate the digit.
Once a match is found, .group(1) extracts the captured digit. This method is overkill for just one digit, but it’s a great technique for more advanced text parsing.
Creating a function to handle negative numbers
def get_last_digit(number):
return abs(number) % 10
print(f"Last digit of 42: {get_last_digit(42)}")
print(f"Last digit of -789: {get_last_digit(-789)}")--OUTPUT--Last digit of 42: 2
Last digit of -789: 9
When you use the modulo operator on a negative number like -789 % 10, Python's behavior might surprise you. It returns 1 instead of 9. To get the actual last digit, you need to handle the negative sign first.
- The
abs()function is the perfect tool for this. It returns the absolute value of a number, turning-789into789. - After that, the standard
% 10operation works as you'd expect.
Encapsulating this logic in a function like get_last_digit() makes your code robust and reusable for any integer.
Working with very large integers
large_number = 10**1000 + 7
last_digit = large_number % 10
print(f"The last digit of this large number is: {last_digit}")--OUTPUT--The last digit of this large number is: 7
One of Python's strengths is its ability to handle arbitrarily large integers without any extra effort. You don't need special libraries for massive numbers; the standard integer type works just fine. This makes finding the last digit of a huge number surprisingly simple.
- The code uses
10**1000 + 7to create an enormous number. - The familiar
% 10operator still works perfectly, instantly isolating the final digit.
This built-in feature is why Python is so popular for scientific computing and other fields where large-number arithmetic is essential.
Move faster with Replit
Replit is an AI-powered development platform with all Python dependencies pre-installed, so you can skip setup and start coding instantly. This means you can go from learning individual techniques, like finding the last digit of a number, to building complete applications much faster.
With Agent 4, you can describe what you want to build, and it will handle everything from writing the code to connecting databases, managing APIs, and deploying your app. Instead of piecing together functions, you can focus on the final product. For example, you could create:
- A checksum validator that uses the last digit of a product ID to confirm its authenticity.
- A data entry tool that checks if a user-inputted number is even or odd by examining its final digit.
- A simple game where the outcome is determined by the last digit of a randomly generated number.
Simply describe your app, and Replit will write the code, test it, and fix issues automatically, all within your browser.
Common errors and challenges
Getting the last digit is usually straightforward, but you'll want to watch out for a few common errors and unexpected behaviors.
Handling negative numbers with the % operator
Python's % operator behaves differently with negative numbers than you might expect. The result of a % n always takes the sign of the divisor n, which can lead to some counterintuitive outcomes.
- For example,
-789 % 10evaluates to1, not-9or9. This is because the divisor,10, is positive, so the remainder must also be positive. - This behavior can be confusing, especially if you're used to other programming languages where the result might take the sign of the dividend.
- As mentioned earlier, the simplest fix is to use
abs()on the number before the modulo operation to ensure you always get the intuitive final digit.
Avoiding division by zero errors with modulo
The modulo operator is a form of division, which means you can't use zero as a divisor. Attempting an operation like number % 0 will immediately crash your program with a ZeroDivisionError. While this might seem obvious, it's a common bug when the divisor is a variable that could accidentally become zero in your code. Always check that a variable is not zero before using it as a divisor.
Dealing with floating-point precision issues
Floating-point numbers, or floats, can introduce precision issues. Because of how computers represent decimal numbers internally, arithmetic operations like modulo don't always produce exact results. For instance, 123.45 % 10 might give you a result like 3.450000000000003 instead of a clean 3.45. This tiny error can cause problems in comparisons and further calculations.
- If you only care about the last digit of the integer part, you should first convert the float to an integer.
- For example, use
int(123.45)to get123. - Then, you can safely use the modulo operator,
123 % 10, to get3.
Handling negative numbers with the % operator
Handling negative numbers with the % operator
Using the % operator with negative numbers in Python doesn't always give you the intuitive last digit. The result is mathematically consistent but can be surprising if you're expecting a simple remainder. The following code demonstrates this common point of confusion.
# Trying to find the last digit of a negative number
number = -123
last_digit = number % 10
print(f"The last digit of {number} is: {last_digit}")
The code outputs 7 instead of 3. With negative numbers, the % operator produces a result with the same sign as the divisor, 10. The following example shows how to adjust the logic to get the intuitive last digit.
# Properly handling negative numbers
number = -123
last_digit = abs(number) % 10
print(f"The last digit of {number} is: {last_digit}")
By wrapping the number in the abs() function, you first convert it to its positive equivalent. This neutralizes the negative sign before the modulo operation takes place. As a result, abs(-123) % 10 is the same as 123 % 10, giving you the expected last digit, 3. You should use this method whenever your program might process negative integers to avoid unexpected results from the % operator.
Avoiding division by zero errors with modulo
Since the modulo operator, %, is a form of division, using zero as a divisor isn't allowed. This action immediately triggers a ZeroDivisionError and crashes your program. The following code demonstrates this error when iterating through a list of divisors.
divisors = [5, 0, 10]
for d in divisors:
result = 100 % d
print(f"100 % {d} = {result}")
The loop processes each number in the divisors list. The error occurs when d becomes 0, as the operation 100 % 0 is invalid. The next example demonstrates how to safely handle this scenario.
divisors = [5, 0, 10]
for d in divisors:
if d != 0:
result = 100 % d
print(f"100 % {d} = {result}")
else:
print(f"Cannot divide by zero")
The fix is to add a simple conditional check. The if d != 0: statement ensures the modulo operation only runs with a non-zero divisor, sidestepping the ZeroDivisionError. This is a crucial safeguard whenever your divisor is a variable that might receive an unexpected zero value—such as from user input or dynamic calculations. It's a simple but effective way to make your code more robust and prevent crashes.
Dealing with floating-point precision issues
Floating-point numbers, or floats, don't always behave as you'd expect because of how computers store decimal values. This can create tiny precision errors that cause unexpected results, especially with operators like %. The following code demonstrates this common pitfall.
a = 0.1 + 0.2
b = 0.3
print(f"a = {a}, b = {b}")
print(f"a % b = {a % b}") # Expected 0.0
The code shows that 0.1 + 0.2 doesn't precisely equal 0.3 due to binary representation. This tiny discrepancy means the modulo operation a % b leaves an unexpected remainder instead of zero. The next example demonstrates how to manage this.
import math
a = 0.1 + 0.2
b = 0.3
print(f"a = {a}, b = {b}")
remainder = a % b
if math.isclose(remainder, 0, abs_tol=1e-9):
print("The remainder is effectively zero")
else:
print(f"The remainder is {remainder}")
The fix is to use Python's math.isclose() function. It checks if the remainder is close enough to 0 to be considered equal, using a small tolerance defined by abs_tol=1e-9. This approach acknowledges that float math isn't always exact and lets you treat near-zero results as zero. It's a reliable way to compare floats after any arithmetic operation to avoid bugs caused by tiny precision errors.
Real-world applications
Now that you've mastered the techniques, you can use this simple operation to solve a surprising range of real-world programming problems.
Using the % operator to check if a number is even or odd
Checking if a number is even or odd is a textbook use for the % operator, as an even number will always have a remainder of 0 when divided by 2.
numbers = [15, 22, 87, 44, 103]
for num in numbers:
if num % 2 == 0:
print(f"{num} is even")
else:
print(f"{num} is odd")
This code iterates through the numbers list to classify each integer. The core of the logic lies in the if num % 2 == 0: condition, which determines the program's flow for each number.
- The modulo operator (
%) is used to test for divisibility by2. - Based on the result, the code prints whether the number is even or odd.
It's a concise way to perform conditional logic on a collection of data, sorting items into two distinct categories.
Implementing a circular buffer with the % operator
The % operator is the key to implementing a circular buffer, a structure that lets you navigate a list of items as if it were a continuous loop.
def circular_access(items, current_position, steps):
new_position = (current_position + steps) % len(items)
return items[new_position], new_position
days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
position = 0 # Start at Monday
# Move forward 10 days (which will wrap around)
day, position = circular_access(days, position, 10)
print(f"10 days after Monday is: {day}")
# Move back 3 days
day, position = circular_access(days, position, -3)
print(f"Going back 3 days gives: {day}")
The circular_access function uses the modulo operator to calculate a new position within a list. This technique ensures that any movement, whether forward or backward, results in a valid index by keeping the position within the list's bounds.
- The core logic is
(current_position + steps) % len(items). - The
%operator finds the remainder when the potential new position is divided by the list's length. - This effectively makes the index wrap around if it goes past the end or before the beginning.
The function returns both the item at the new index and the index itself, so you can easily track your current spot.
Get started with Replit
Turn these techniques into a real tool. Describe what you want to build, like “Create a script that validates ID numbers using the Luhn algorithm” or “Build a tool that sorts data into groups based on the last digit.”
Replit Agent will write the code, test for errors, and deploy the app for you. It handles the development workflow from a simple prompt. Start building with Replit.
Create and deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.
Create and deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.



