Write a Python Program to Reverse a Number

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:

  1. Convert the number to a string
  2. Reverse the string
  3. 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_num

Let’s break down the code line by line:

  • The reverse_number function takes a number num as input.
  • We convert the number to a string using the str function and store it in the num_str variable.
  • 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 int function and store it in the reversed_num variable.
  • 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.