For working professionals
For fresh graduates
More
Python Tutorials - Elevate You…
1. Introduction to Python
2. Features of Python
3. How to install python in windows
4. How to Install Python on macOS
5. Install Python on Linux
6. Hello World Program in Python
7. Python Variables
8. Global Variable in Python
9. Python Keywords and Identifiers
10. Assert Keyword in Python
11. Comments in Python
12. Escape Sequence in Python
13. Print In Python
14. Python-if-else-statement
15. Python for Loop
16. Nested for loop in Python
17. While Loop in Python
18. Python’s do-while Loop
19. Break in Python
20. Break Pass and Continue Statement in Python
21. Python Try Except
22. Data Types in Python
23. Float in Python
24. String Methods Python
25. List in Python
26. List Methods in Python
27. Tuples in Python
28. Dictionary in Python
29. Set in Python
30. Operators in Python
31. Boolean Operators in Python
32. Arithmetic Operators in Python
33. Assignment Operator in Python
34. Bitwise operators in Python
35. Identity Operator in Python
36. Operator Precedence in Python
37. Functions in Python
38. Lambda and Anonymous Function in Python
39. Range Function in Python
40. len() Function in Python
41. How to Use Lambda Functions in Python?
42. Random Function in Python
43. Python __init__() Function
44. String Split function in Python
45. Round function in Python
46. Find Function in Python
47. How to Call a Function in Python?
48. Python Functions Scope
49. Method Overloading in Python
50. Method Overriding in Python
51. Static Method in Python
52. Python List Index Method
53. Python Modules
54. Math Module in Python
55. Module and Package in Python
56. OS module in Python
57. Python Packages
58. OOPs Concepts in Python
59. Class in Python
60. Abstract Class in Python
61. Object in Python
62. Constructor in Python
63. Inheritance in Python
64. Multiple Inheritance in Python
65. Encapsulation in Python
66. Data Abstraction in Python
67. Opening and closing files in Python
68. How to open JSON file in Python
69. Read CSV Files in Python
70. How to Read a File in Python
71. How to Open a File in Python?
72. Python Write to File
73. JSON Python
74. Python JSON – How to Convert a String to JSON
75. Python JSON Encoding and Decoding
76. Exception Handling in Python
77. Recursion in Python
78. Python Decorators
79. Python Threading
80. Multithreading in Python
81. Multiprocеssing in Python
82. Python Regular Expressions
83. Enumerate() in Python
84. Map in Python
85. Filter in Python
86. Eval in Python
87. Difference Between List, Tuple, Set, and Dictionary in Python
88. List to String in Python
89. Linked List in Python
90. Length of list in Python
91. Python List remove() Method
92. How to Add Elements in a List in Python
93. How to Reverse a List in Python?
94. Difference Between List and Tuple in Python
95. List Slicing in Python
96. Sort in Python
97. Merge Sort in Python
98. Selection Sort in Python
99. Sort Array in Python
100. Sort Dictionary by Value in Python
101. Datetime Python
102. Random Number in Python
103. 2D Array in Python
104. Abs in Python
105. Advantages of Python
106. Anagram Program in Python
107. Append in Python
108. Applications of Python
109. Armstrong Number in Python
110. Assert in Python
111. Binary Search in Python
112. Binary to Decimal in Python
113. Bool in Python
114. Calculator Program in Python
115. chr in Python
116. Control Flow Statements in Python
117. Convert String to Datetime Python
118. Count in python
119. Counter in Python
120. Data Visualization in Python
121. Datetime in Python
122. Extend in Python
123. F-string in Python
124. Fibonacci Series in Python
125. Format in Python
126. GCD of Two Numbers in Python
127. How to Become a Python Developer
128. How to Run Python Program
129. In Which Year Was the Python Language Developed?
130. Indentation in Python
131. Index in Python
132. Interface in Python
133. Is Python Case Sensitive?
134. Isalpha in Python
135. Isinstance() in Python
136. Iterator in Python
137. Join in Python
138. Leap Year Program in Python
139. Lexicographical Order in Python
140. Literals in Python
141. Matplotlib
142. Matrix Multiplication in Python
143. Memory Management in Python
144. Modulus in Python
145. Mutable and Immutable in Python
146. Namespace and Scope in Python
147. OpenCV Python
148. Operator Overloading in Python
149. ord in Python
150. Palindrome in Python
151. Pass in Python
152. Pattern Program in Python
153. Perfect Number in Python
154. Permutation and Combination in Python
155. Prime Number Program in Python
156. Python Arrays
157. Python Automation Projects Ideas
158. Python Frameworks
159. Python Graphical User Interface GUI
160. Python IDE
161. Python input and output
162. Python Installation on Windows
163. Python Object-Oriented Programming
164. Python PIP
165. Python Seaborn
166. Python Slicing
167. type() function in Python
168. Queue in Python
169. Replace in Python
170. Reverse a Number in Python
Now Reading
171. Reverse a string in Python
172. Reverse String in Python
173. Stack in Python
174. scikit-learn
175. Selenium with Python
176. Self in Python
177. Sleep in Python
178. Speech Recognition in Python
179. Split in Python
180. Square Root in Python
181. String Comparison in Python
182. String Formatting in Python
183. String Slicing in Python
184. Strip in Python
185. Subprocess in Python
186. Substring in Python
187. Sum of Digits of a Number in Python
188. Sum of n Natural Numbers in Python
189. Sum of Prime Numbers in Python
190. Switch Case in Python
191. Python Program to Transpose a Matrix
192. Type Casting in Python
193. What are Lists in Python?
194. Ways to Define a Block of Code
195. What is Pygame
196. Why Python is Interpreted Language?
197. XOR in Python
198. Yield in Python
199. Zip in Python
Reversing a number in Python can be a useful operation in many programming tasks. The challenge comes in choosing the right method to reverse the digits efficiently.
It’s a common task for beginners to grasp, but once you understand the basic concepts, it becomes a straightforward operation.
In this tutorial, you’ll learn about how the different methods work and when to use them.
Let’s dive in!
"Boost your Python skills with our Data Science and Machine Learning courses from top universities — take the next step in your learning journey today!"
The concept of reverse a number in Python using while loop is a great way to practice looping and number manipulation.
Here’s how we can reverse a number like 12345 using a while loop:
# initialize the number and set up the result variable
number = 12345
reversed_number = 0
#loop through each digit until the number becomes 0
while number > 0:
# Extract the last digit
digit = number % 10 # this gives us the last digit of the number
reversed_number = reversed_number * 10 + digit # shift the current reversed number by one place and add the digit
#remove the last digit from the original number
number = number // 10 # This reduces the number by removing the last digit
#print the reversed number
print("Reversed number:", reversed_number)
Output:
Reversed number: 54321
Explanation:
We start by setting the number we want to reverse, 12345, and initialize reversed_number to 0. This variable will store the reversed version as we process each digit.
The while loop continues as long as the number is greater than 0. Inside the loop, we extract the last digit of the number using the modulus operator %. For example, 12345 % 10 gives us the last digit, 5.
Once we have the last digit, we update reversed_number. To do this, we first multiply reversed_number by 10 (to shift its digits one place to the left) and then add the current digit to it. This ensures the new digit is added to the right of the previously reversed number. For example, after the first iteration, reversed_number becomes 5.
After extracting the last digit, we reduce the original number by dividing it by 10 (using integer division //). This removes the last digit, so in the first iteration, the number becomes 1234, then 123, and so on until it becomes 0.
Finally, once the loop ends (when the number becomes 0), we print the reversed number, which in this case will be 54321.
Key Takeaways:
"Kickstart your coding journey with our free Python courses, tailored just for you — master Python programming fundamentals, explore essential libraries, and work on practical case studies!"
The concept of reverse a number in Python for loop involves first converting the number into a string and then iterating over each digit in reverse order. This is an efficient way to reverse a number and gives you good practice with string manipulation.
Let’s reverse the number 6789 using a for loop:
# initialize the number
number = 6789
# convert the number to a string for easy iteration
str_number = str(number) # convert the number to a string
#initialize the reversed number variable
reversed_number = 0
#loop through each digit in reverse order
for digit in str_number:
#update the reversed number
reversed_number = reversed_number * 10 + int(digit) # multiply by 10 to shift and add the digit
# print the reversed number
print("Reversed number:", reversed_number)
Output:
Reversed number: 9876
Explanation:
We start with the number 6789 and initialize it as a number.
To easily iterate through each digit of the number, we convert it into a string using str(). This makes it easier to loop through each individual digit. After conversion, str_number becomes '6789'.
We initialize a variable reversed_number to 0. This will hold the reversed number as we process each digit.
We use a for loop to iterate through each character (digit) in str_number. Since str_number is a string, each iteration gives us a digit as a string, which we then convert back to an integer using int().
In each iteration of the loop, we multiply the current value of reversed_number by 10 (to shift the digits to the left) and add the current digit. This effectively builds the reversed number from right to left.
After the loop finishes, we print the reversed_number, which now holds the reversed value of the original number.
Key Takeaways:
Also Read: Python Program to Convert List to String
This method of reversing numbers using a for loop is useful when you prefer working with strings or need to apply additional string manipulation.
Recursion can be used to reverse a number in Python by repeatedly extracting the last digit and appending it to the result. The function calls itself with the remaining digits until the number becomes 0, at which point the recursion stops, and the reversed number is returned.
Let’s reverse the number 1234 using a recursive function.
# define the recursive function
def reverse_number(n, reversed_num=0):
#base case: When n becomes 0, return the reversed number
if n == 0:
return reversed_num
# extract the last digit and build the reversed number
digit = n % 10 # get the last digit
reversed_num = reversed_num * 10 + digit # add it to the reversed number
# recur with the remaining number
return reverse_number(n // 10, reversed_num)
# call the function with the original number
number = 1234
reversed_number = reverse_number(number)
print("Reversed number:", reversed_number)
Output:
Reversed number: 4321
Explanation:
We define a function reverse_number that takes two parameters: n (the number to reverse) and reversed_num (which will hold the reversed number). Initially, reversed_num is set to 0.
The base case is when n becomes 0. At this point, we return the reversed_num, which holds the reversed number.
We extract the last digit of n using the modulus operator (% 10). This gives us the rightmost digit of the number.
We update reversed_num by multiplying it by 10 (to shift the digits) and adding the extracted digit.
We call the reverse_number function recursively, passing the integer division of n by 10 (n // 10) to remove the last digit and continue the process until the base case is met.
We call the reverse_number function with 1234, and it returns 4321 after the recursion completes.
Key Takeaways:
Also Read: Recursive Feature Elimination: What It Is and Why It Matters?
In this approach, you convert the number to a string and use slicing to reverse the string. This method is both compact and intuitive, making it ideal for beginners and those who want a straightforward solution to reverse a number.
#convert the number to a string
number = 98765
str_number = str(number)
# use string slicing to reverse the string
reversed_str = str_number[::-1]
# convert the reversed string back to an integer
reversed_number = int(reversed_str)
# print the reversed number
print("Reversed number:", reversed_number)
Output:
Reversed number: 56789
Explanation:
First, we convert the number 98765 to a string using str(number). This allows us to manipulate the digits easily as characters.
The key here is using string slicing. The syntax [::-1] is a shorthand to reverse the string. It means:
So, str_number[::-1] reverses the string '98765' to '56789'.
After reversing the string, we convert it back to an integer using int(). This gives us the reversed number in its integer form.
Finally, we print the reversed number, which is 56789.
Key Takeaways:
Also Read: Different Ways of String formatting in Python: Top 3 Methods
Unlike other methods, reversed() works with any iterable, including strings and lists. To reverse a number using this method, we’ll first convert it to a string, reverse the string, and then convert it back to an integer.
# convert the number to a string
number = 8901
str_number = str(number)
# reverse the string using the reversed() method
reversed_str = ''.join(reversed(str_number))
# convert the reversed string back to an integer
reversed_number = int(reversed_str)
# print the reversed number
print("Reversed number:", reversed_number)
Output:
Reversed number: 1098
Explanation:
The first step is to convert the number 8901 into a string using str(number). This step is necessary because the reversed() method works only on iterable objects like strings or lists.
We apply the reversed() method to the string str_number. The reversed() function returns an iterator that produces the string's characters in reverse order. We then use ''.join()'' to join these characters back into a single string.
After reversing the string, we convert it back to an integer using int(). This gives us the reversed number.
Finally, we print the reversed number, which in this case is 1098.
Key Takeaways:
If you're looking for an alternative to string slicing, this method is a great option.
Reversing a number in Python using a list is a simple and effective approach that builds on the concept of manipulating a sequence of digits.
Let’s break this process into clear steps.
#convert the number into a string
number = 45891
str_number = str(number)
#convert the string into a list of characters (digits)
digit_list = list(str_number)
#reverse the list using slicing
reversed_list = digit_list[::-1]
#join the reversed list into a string
reversed_str = ''.join(reversed_list)
#convert the reversed string back to an integer
reversed_number = int(reversed_str)
#print the reversed number
print("Reversed number:", reversed_number)
Output:
Reversed number: 19854
Explanation:
The number 45891 is converted into a string using str(number). This allows you to treat each digit as an individual character.
Using the list() function, the string is broken down into a list of its individual digits: ['4', '5', '8', '9', '1'].
The slicing technique [::-1] reverses the order of elements in the list. The result is ['1', '9', '8', '5', '4'].
Using ''.join(reversed_list), the reversed list of digits is combined back into a single string: "19854".
Finally, the reversed string is converted back to an integer using int(). This ensures the output is a numeric value, not a string.
The print() statement outputs the reversed number, which is 19854.
Key Takeaways:
A stack in Python operates on the principle of Last In, First Out (LIFO), meaning the last element added is the first one removed.
Let’s look at this step-by-step.
#convert the number into a string
number = 34567
str_number = str(number)
#initialize an empty stack
stack = []
#push each digit of the number into the stack
for digit in str_number:
stack.append(digit)
#pop digits from the stack to form the reversed string
reversed_str = ''
while stack:
reversed_str += stack.pop()
#convert the reversed string back to an integer
reversed_number = int(reversed_str)
#print the reversed number
print("Reversed number:", reversed_number)
Output:
Reversed number: 76543
Explanation:
The number 34567 is converted into a string using str(number), so each digit can be processed individually.
We use a Python list (stack = []) as a stack. Lists in Python allow us to mimic stack operations like push (append) and pop.
Using a for loop, each digit from the string str_number is added to the stack with stack.append(digit). The stack now looks like this: ['3', '4', '5', '6', '7'].
Using a while loop, we repeatedly remove the top digit from the stack with stack.pop() and add it to reversed_str. The LIFO nature of the stack ensures the digits are retrieved in reverse order. The final reversed string is "76543".
The reversed string is converted back to a number using int(reversed_str), ensuring the output is a numeric value.
The print() statement outputs the reversed number, which is 76543.
Key Takeaways:
Try implementing this yourself! Stacks are a fundamental data structure in computer science, and this exercise is a great way to understand their practical application.
Also Read: How to Implement Stacks in Data Structure? Stack Operations Explained
You can reverse a number in Python using a for loop by converting the number to a string, iterating over the digits in reverse order, and then converting the reversed sequence back to an integer.
The simplest way is to use a for loop combined with slicing or the reversed() function to iterate through the digits in reverse and construct the reversed number.
Yes, you can reverse a number in Python using a while loop by extracting the digits one by one using modulus (%) and division (//) until the number becomes zero, and then constructing the reversed number.
It depends on your preference and use case. If you prefer to work with strings, reverse a number in Python using a for loop is easier. For numeric operations, reversing a number in Python using a while loop is more straightforward.
Yes, when using a for loop, you need to convert the number to a string because a for loop iterates over sequences like strings or lists.
You can reverse a number in Python using a while loop by performing arithmetic operations to extract and rearrange the digits without converting to a string.
Python automatically removes leading zeros in integers. For example, reversing 120 will give 21 instead of 021.
Yes, you can handle negative numbers by first converting the number to a string, excluding the negative sign, reversing the digits, and reapplying the negative sign to the result.
Yes, but you would treat it as a string. Reverse the digits, including the decimal point, and then convert it back to a floating-point number if needed.
Learning this technique enhances your understanding of loops, string manipulation, and number processing, which are essential skills in Python programming.
Yes, you can use a list comprehension to reverse the digits of a number by converting it into a string, iterating in reverse, and then converting it back to an integer. However, this is more commonly done with a for loop or slicing.
Take our Free Quiz on Python
Answer quick questions and assess your Python knowledge
Author
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.