Open In App

Python Program to Reverse a Number

Last Updated : 26 Feb, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

We are given a number and our task is to reverse its digits. For example, if the input is 12345 then the output should be 54321. In this article, we will explore various techniques for reversing a number in Python.

Using String Slicing

In this example, the Python code reverses a given number by converting it to a string, slicing it in reverse order and then converting it back to an integer. The original and reversed numbers are printed for the example case where the original number is 1234.

n1 = 1234
rev_num = int(str(n1)[::-1])

print(n1)
print(rev_num)

Output
1234
4321

Explanation:

  • number n1 is converted to a string and reversed using slicing ([::-1]).
  • reversed string is then converted back to an integer.

Using While Loop

In this example, the Python code reverses a given number using a while loop. It prints both the original and reversed numbers. The example demonstrates reversing the number 6789.

n1 = 6789
rev = 0

while n1 > 0:
    digit = n1 % 10
    rev = rev * 10 + digit
    n1 //= 10

print(6789)
print(rev)

Output
6789
9876

Explanation:

  • number n1 is processed by repeatedly extracting its last digit, appending it to rev, and then removing the last digit from n1 using the // operator.
  • The original number (6789) and the reversed number are printed

Using For Loop

In this example, the Python code reverses a given number by iterating through its digits using a for loop. It prints both the original and reversed numbers. The example demonstrates reversing the number 6789.

n1 = 6789
rev = 0

for _ in str(n1):
    digit = n1 % 10
    rev = rev * 10 + digit
    n1 //= 10

print(6789)
print(rev)

Output
6789
9876

Explanation:

  • number n1 is processed by converting it to a string and using a for loop to extract each digit from the number.
  • The digits are added to rev to build the reversed number.
  • Finally, the original number (6789) and the reversed number are printed.

Using Recursion

In this example, in below code Python function `reverse_number` recursively reverses a given number by extracting the last digit and placing it at the appropriate position. The recursion continues until the original number is fully reversed. The example demonstrates reversing the number 987654.

def reverse_number(n):
    if n == 0:
        return 0
    else:
        return (n % 10) * 10 ** (len(str(n)) - 1) + reverse_number(n // 10)


# Example
num = 987654
orig_num = num
rev_num = reverse_number(num)
print(orig_num)
print(rev_num)

Output
987654
456789


Article Tags :
Practice Tags :

Similar Reads

three90RightbarBannerImg