How to reverse a given number in Python
In this Answer, our goal is to reverse the given number (an integer input), as shown below:
We can create a solution for the specified objective or problem statement in various ways, like using a while loop iteration or string slicing to reverse the given number. Let’s look at both approaches to reverse a number in Python.
Using the while loop iteration
In this approach, we use a while loop to iterate the given number if it is greater than 0. Within the loop, we calculate the remainder of the given number using the modulus operator to extract the last digit. Then, we multiply the current reverse value by 10, which shifts the digits one place to the left, and we add the remainder to the resultant number. Finally, we update the given number by performing integer division by 10, which discards its last digit.
Code
Let’s implement this approach in Python to reverse a number using while loop iteration, as follows:
given_number = int(input())# Check if the given number is negativeis_negative = Falseif given_number < 0:is_negative = Truegiven_number = abs(given_number)# Reverse the given numberoriginal_number = given_numberreversed_number = 0while given_number > 0:remainder = given_number % 10reversed_number = (reversed_number * 10) + remaindergiven_number = given_number // 10# Add negative sign to the reversed number if the given number was negativeif is_negative:reversed_number *= -1print(f"Original number: {original_number}")print(f"Reversed number: {reversed_number}")
Enter the input below
Note: Before pressing the “Run” button, enter a number in the “Enter the input below” field.
Explanation
Let’s discuss the code above:
Lines 1–7: We start by taking an integer input from the user using the
int()function. Then, we check if the given number is negative. If it is negative, we set theis_negativeflag toTrueand take the absolute value of the given number using theabs()function. This step ensures that we work with the absolute value of the number for the reversal process.Lines 10–15: We proceed with the reversal process. We initialize
original_numberto store the original value ofgiven_number, andreversed_numberto store the reversed number. Using awhileloop, we extract digits fromgiven_numberone by one (calculating theremainderwhen divided by10), add them toreversed_number, and remove them fromgiven_numberuntilgiven_numberbecomes zero.Lines 18–19: After the reversal process, if the original number was negative (indicated by the
is_negativeflag), we apply a negative sign to thereversed_numberto maintain the sign consistency.Lines 21–22: Finally, we print both the original number (
original_number) and the reversed number (reversed_number).
Now that we understand how to reverse a number using a while loop, let’s explore Python’s string slicing capabilities to provide a more straightforward approach to reversing a number.
Using the string slicing
In this approach, after taking the input number from the user, we first check if it is negative and store this information. Then, instead of manipulating integers directly, we convert the number to a string. By converting the number to a string, we gain access to powerful string manipulation methods, including string slicing. Python’s string slicing allows us to effortlessly reverse a string by specifying a slicing step of -1. This step indicates that we want to traverse the string in reverse order.
Code
Here’s the implementation of this string slicing approach in Python to reverse the number:
given_number = int(input())# Check if the given number is negativeis_negative = Falseif given_number < 0:is_negative = Truegiven_number = abs(given_number)# Convert the number to a string to reverse it using string slicingoriginal_number_str = str(given_number)reversed_number_str = original_number_str[::-1]# Convert the reversed string back to an integerreversed_number = int(reversed_number_str)# Add negative sign to the reversed number if the given number was negativeif is_negative:reversed_number *= -1print(f"Original number: {given_number}")print(f"Reversed number: {reversed_number}")
Enter the input below
Note: Here, we have provided an explanation of the code segment that differs from the previous implementation.
Explanation
Let’s discuss the code above:
Line 10: Convert the number to a string using the
str()function so we can reverse it using slicing.Line 11: Reverse the string using slicing
[::-1].Line 14: Convert the reversed string back to an integer using the
int()function.
By leveraging Python’s string manipulation capabilities, we achieved the same result with fewer lines of code and increased readability. This demonstrates the flexibility and power of Python’s built-in functions and methods for handling common programming tasks.
Conclusion
We’ve successfully coded the solutions to reverse a given number in Python. Now, the next time someone asks you, “How to reverse a given number in Python?” you can share the knowledge and code it. Happy coding!
Can we use this code for negative numbers?
Free Resources