Python program to Reverse a Number

In this tutorial, we will discuss a Python program to reverse a number.

Before going to the program first, let us understand what is a Reverse Number.

Reverse Number:

  • The reverse of a number is a mathematical method to obtain from a number another written in the opposite way to the first.
  • For example, reversing the number 1234 gives 4321.

Related: Python Program to Check Leap Year

Program code to reverse a number using Python

# Reverse a Number in Python
def reverse_number(num):
    return int(str(num)[::-1])

number = int(input("Enter a number: "))
print(f"The reverse of {number} is {reverse_number(number)}.")

Explanation

  1. Function Definition: The reverse_number function takes an integer num as input and returns the reverse of the number.
  2. Reverse Calculation: The function converts the number to a string, reverses the string using slicing, and converts it back to an integer.
  3. Main Program: The program prompts the user to enter a number and then calculates the reverse of the number using the reverse_number function.

Output

Python program to Reverse a Number

  • When you run the above program, it will prompt you to enter a number. After entering the number, it will reverse the number and print the result.

Conclusion

  • In this tutorial, we learned how to reverse a given number using a Python program.
  • Understanding this concept is essential for solving various mathematical problems and competitive programming challenges.
  • Practice this example to enhance your programming skills and understanding of number manipulation.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *