Python Program to Reverse Number
A reverse number is a number that is just opposite to the number. The reverse number contains all the digits but in reverse order. For example, the reverse of 2545 will be 5452 which is quite opposite of it. In python, we can do this by using several ways such as iterative way, string slicing, etc. Let's see some examples.
Reverse a Number in Python
This Python program uses a while loop to get the reverse number. This is a simple approach where we take user input and then first, convert that into an integer after that uses a while loop to iterate each digit and get a reverse integer value.
# Python Program to Reverse a Number number = input("Enter a Number") number = int(number) # Convert input to integer reverse_number = 0 temp = number # Getting reverse number while number > 0: digit = number % 10 reverse_number = reverse_number*10+digit number //= 10 print("Original Number: ",temp) print("Reverse Number: ",reverse_number)
Enter a Number 58452
Original Number: 58452
Reverse Number: 25485
Reverse A Number using String Slicing in Python
This is the simplest solution where we are using the string slicing technique. We simply return a string in reverse order with indexing. The -1 index represents the last element in the string.
# Python Program to Reverse a Number number = input("Enter a Number") reverse_number = 0 # Getting reverse number reverse_number = number[::-1] print("Original Number: ",number) print("Reverse Number: ",reverse_number)
Enter a Number 54321
Original Number: 54321
Reverse Number: 12345