Python Tutorials

Python Programs

Python Reverse a Number


Python Reverse a Number

In this tutorial, we will learn how to reverse a number in Python. We will cover the basic concept of number manipulation and implement a function to perform the reversal.


What is Number Manipulation

Number manipulation involves performing operations on numbers to achieve a specific result. Reversing a number means rearranging its digits in the opposite order.


Syntax

The syntax to reverse a number in Python is:

def reverse_number(n):
    reversed_num = int(str(n)[::-1])
    return reversed_num


Reversing a number

We can create a function to reverse a given number by converting it to a string, reversing the string, and converting it back to an integer.

For example,

  1. Define a function named reverse_number that takes one parameter n.
  2. Convert the number to a string.
  3. Reverse the string using slicing with [::-1].
  4. Convert the reversed string back to an integer.
  5. Return the reversed number.
  6. Call the function with a sample number and print the result.

Python Program

def reverse_number(n):
    reversed_num = int(str(n)[::-1])
    return reversed_num

# Sample number
sample_number = 12345

# Reverse the number
result = reverse_number(sample_number)

# Print the result
print('Reversed number is:', result)

Output

Reversed number is: 54321