Python program to reverse a number
In this post, you will learn how to write a Python program to reverse a number. Such a type of question can improve your logical problem solving skills.
Python program to reverse a number using while loop
In the given Python program, we have asked the user to enter an integer number. The while loop is used and the last digit of the number is obtained by using the modulus operator. The last digit is then stored at the one's place, second last at the ten's place and so on. The last digit is then removed by truly dividing the number with 10. This loop terminates when the value of the number is 0. Then, the reverse of the number is printed.
# user input
num = int(input("Enter the number: "))
# Initiate value to null
rev_num = 0
# reverse the integer number using the while loop
while (num > 0):
remainder = num % 10
rev_num = (rev_num * 10) + remainder
num = num // 10
# Display the result
print("The reverse number : {}".format(rev_num))
Output of the above code:
Enter the number: 98235781
The reverse number : 18753289
Python program to reverse a number using for loop
Here, we have used the for loop to reverse a number using Python programming language.
# Python program to reverse a number
# using for loop
# user input
num = input("Enter the number: ")
# calculating reverse of number
reverse = ''
for i in range(len(num), 0, -1):
reverse += num[i-1]
# print reverse of number
print('Reverse number: ', reverse)
Output of the number:
Enter the number:
987645
Reverse number: 546789
Python program to reverse a number using recursion
Recursion function is a function that is called itself. In the given example, we call the recursion function to get the reverse of a number. A recursion function continues until some condition is met to prevent it. That's why, we use the if statement to break the infinite recursion. In the given Python program, we have used recursion to reverse a given number-
num = int(input("Enter the number: "))
rev_num = 0
def reverse_num(num):
global rev_num
if (num > 0):
Reminder = num % 10
rev_num = (rev_num * 10) + Reminder
reverse_num(num // 10)
return rev_num
rev_num = reverse_num(num)
print("Reverse of entered number: %d" % rev_num)
Output of the above code:
Enter the number: 98765421
Reverse of entered number: 12456789
Related Articles
Convert Python list to numpy arrayConvert string to list Python
Python program to list even and odd numbers of a list
Python loop through list
Sort list in descending order Python
Convert array to list Python
Python take screenshot of specific window
Web scraping Python BeautifulSoup
Check if two strings are anagrams Python
Python program to add two numbers
Print new line python
Python for loop index
Convert List to Dataframe Python
numpy random choice
Dictionary inside list python
Check if list is empty Python
Python raise keyword
Python program to get the largest number from a list
Python program to map two lists into a dictionary