Contents Table of Contents
Python Program to Reverse a NumberIn this tutorial, we will learn different ways to reverse a number. Some of the possible ways are given in the below list.
Example 1: Reverse Number using String slicingIn this example, we convert given number to string using str() and then reverse it using string slicing. The reversed string is converted back to int. If the given input is not a number, we shall print a message to the user. Python Program
Output
Example 2: Reverse Number using While LoopIn this program we shall use while loop to iterate over the digits of the number by popping them one by one using modulo operator. Popped digits are appended to form a new number which would be our reversed number. Python Program
Output
SummaryIn this tutorial of Python Examples, we learned how to reverse a number using while loop and string slicing. Related Tutorials
In this tutorial, you’ll learn how to use Python to reverse a number. While this is similar to learning how to reverse a string in Python, which you can learn about here, reversing a number allows us to use math to reverse our number. You’ll learn how to use a Python while loop, string indexing, and how to create an easy-to-read function to reverse a number in Python. The Quick Answer: Use a Python While Loop
Reverse a Python Number Using a While LoopPython makes it easy to
reverse a number by using a while loop. We use a while loop with the help of both floor division and the modulus Let’s take a look at an example to see how this works and then dive into the why of this works: number = 67890 reversed_number = 0 while number != 0: digit = number % 10 reversed_number = reversed_number * 10 + digit number //= 10 print(reversed_number) # Returns: 9876 Let’s break down what we do here:
It’s important to note, this appraoch only works for integers and will not work for floats. In the next section, you’ll learn how to use Python string indexing to reverse a number. Want to learn more about Python list comprehensions? Check out this in-depth tutorial that covers off everything you need to know, with hands-on examples. More of a visual learner, check out my YouTube tutorial here. Reverse a Python Number Using String IndexingAnother way that we can reverse a number is to use string indexing. One of the benefits of this approach is that this approach will work with both integers and floats. In order to make this work, we first turn the number into a string, reverse it, and turn it back into a number. Since we’ll need to convert it back to its original type, we need to first check the numbers type. Let’s take a look at how we can accomplish this in Python: number = 67890.123 reversed_number_string = str(number)[::-1] if type(number) == float: reversed_number = float(reversed_number_string) elif type(number) == int: reversed_number = int(reversed_number_string) print(reversed_number) # Returns 321.09876 Python indexing allows us to iterate over an iterable object, such as a string. The third parameter is optional, but represents the step counter, meaning how to traverse an item. By default, the value is We use the type checking in order to determine what type of number to return back to. In the next section, you’ll learn how to create a custom function that makes the code easier to follow and understand. Want to learn how to use the Python Reverse a Python Number Using a Custom FunctionIn this section, you’ll learn how to turn what you learned in the section above into an easy to read function. While the code may seem intuitive as we write it, our future readers may not agree. Because of this, we can turn our code into a function that makes it clear what our code is hoping to accomplish. Let’s take a look at how we can accomplish this in Python: def reverse_number(number): """Reverses a number (either float or int) and returns the appropriate type. Args: number (int|float): the number to reverse Returns: int|float: the reversed number """ if type(number) == float: return float(str(number)[::-1]) elif type(number) == int: return int(str(number)[::-1]) else: print('Not an integer or float') print(reverse_number(12345.43)) print(reverse_number(456)) # Returns: # 34.54321 # 654 Our function accepts a single parameter, a number. The function first checks what the type is. If the type is either Want to learn more about Python f-strings? Check out my in-depth tutorial, which includes a step-by-step video to master Python f-strings! ConclusionIn this post, you learned how to reverse a number using both math and string indexing. You also learned how to convert the string indexing method to a function that will make it clear to readers of your code what your code is doing. If you want to learn more about string indexing in Python, check out the official documentation for strings here. How do you reverse a number in a for loop?Reverse a number using for loop. public class ReverseNumberExample2.. public static void main(String[] args). int number = 123456, reverse = 0;. //we have not mentioned the initialization part of the for loop.. for( ;number != 0; number=number/10). Can you do a for loop backwards in Python?To reverse for loop in Python just need to read the last element first and then the last but one and so on till the element is at index 0. You can do it with the range function, List Comprehension, or reversed() function. How do you reverse a list in a for loop Python?3) Using for loop Another way to reverse python list without the use of any build-in methods is using loops. Create an empty list to copy the reversed elements. In the for loop, add the iterator as a list element at the beginning with the new list elements. So in that way, the list elements will be reversed. How do you reverse input in Python?Use reversed() Method to Reverse a String in Python You can also use the reversed method in Python which returns a reversed object or iterator of the input string. The only thing you need to do is to perform an additional join operation on the resultant reversed object and return the new string. |