In this tutorial, we will see Python programs to reverse a number. For example, if the input is 95401, then the output should be 10459. We can apply multiple logics to reverse a number in Python. Following are the methods we are going to explore in this Python tutorial:
- While loop
- For loop
- Recursion
- String slicing
- Reversed method
Also Read: Python Program to Find Sum of Digits [5 Methods]
Python Program To Reverse A Number Using While Loop
Code:
Num = 95401 ReverseNumber = 0 while Num != 0: digit = Num % 10 ReverseNumber = ReverseNumber * 10 + digit Num //= 10 print("Reversed Number: " + str(ReverseNumber))
Output:
Also Read: Python Program To Check If A Number Is Perfect Square
Python Program to Reverse a Number Using For Loop
Code:
def reverse_for_loop(per): emptyString = '' for i in per: emptyString = i + emptyString return emptyString num = '95401' if __name__ == "__main__": print('Reversing the given number using for loop =', reverse_for_loop(num))
Output:
Also Read: Increment and Decrement Operators in Python
Python Program to Reverse a Number Using Recursion
Code:
def reverse(n, r): if n==0: return r else: return reverse(n//10, r*10 + n%10) num = int(input("Enter number: ")) reverseNum = reverse(num,0) print("Reverse of %d is %d" %(num, reverseNum))
Output:
Also Read: Python Dictionary Length [How To Get Length]
Python Program to Reverse a Number Using String Slicing
Code:
num = 95401 print(str(num)[::-1])
Output:
Also Read: How To Concatenate Arrays in Python [With Examples]
Python Program to Reverse a Number Using Reversed Method
Code:
def reverse(string): string = "".join(reversed(string)) return string num = "95401" print (num) print ("Reverse of the given number is : ",end="") print (reverse(num))
Output:
Also Read: What Does The Python Percent Sign Mean?
Python Program To Reverse A Number Using Function
Code:
def ReverseNum(): Num = 95401 ReverseNumber = 0 while Num != 0: digit = Num % 10 ReverseNumber = ReverseNumber * 10 + digit Num //= 10 print("Reversed Number: " + str(ReverseNumber)) ReverseNum()
Output:
Also Read: How to Create an Empty Array In Python
Summary
In this Python tutorial, we explored how to reverse a number using various methods such as while loop, for loop, string slicing, recursion, and custom function.
Other related tutorials:
- What Is Python Used For? Applications of Python
- How To Display A Calendar In Python
- How To Sort a List of Tuples in Python
- Arithmetic Operators in Python [With Examples]
- How to Handle String Index Out of Range Error In Python
Hello Friends! I am Himanshu, a hobbyist programmer, tech enthusiast, and digital content creator.
With CodeItBro, my mission is to promote coding and help people from non-tech backgrounds to learn this modern-age skill!