In this tutorial, we’ll learn how to reverse a number in Python. Reversing a number means to reverse the order of its digits.
For example, if we reverse the number 12345, we get 54321.
To reverse a number in Python, we can use the following steps:
- Convert the number to a string
- Reverse the string
- Convert the reversed string back to an integer
Here is the Python code that implements these steps:
def reverse_number(num):
# Convert the number to a string
num_str = str(num)
# Reverse the string
reversed_str = num_str[::-1]
# Convert the reversed string back to an integer
reversed_num = int(reversed_str)
# Return the reversed number
return reversed_numLet’s break down the code line by line:
- The
reverse_numberfunction takes a numbernumas input. - We convert the number to a string using the
strfunction and store it in thenum_strvariable. - We reverse the string using the slicing operator
[::-1]. This creates a new string that is the reverse of the original string. - We convert the reversed string back to an integer using the
intfunction and store it in thereversed_numvariable. - Finally, we return the reversed number.
Here is an example of how to use the reverse_number function:
reverse_number(12345) 54321
That’s it!
We’ve successfully reversed a number in Python using just a few lines of code.




