Write a Program to Reverse a Number in Python

Write a Program to Reverse a Number in Python

Ever wanted to flip numbers backward just for fun? Like turning 123 into 321? Well, writing a Python program to reverse a number is not only a playful exercise but also a good way to get comfortable with the number and string manipulation in code! So, let’s dive into how we can Reverse numbers around with a few lines of Python!

Reverse a number is a common programming task that involves reversing the order of the digits in a given number. We are going to learn different techniques in this article including reversing the number using a while loop, Slicing, and the reversed() method to create a reversed iterable object

12345 => 54321

Introduction

Python is a popular programming language that offers various techniques to perform this task efficiently. In this article, we will explore different ways to reverse a number in Python using code examples. We will walk through step-by-step explanations and provide code snippets to demonstrate each method. Whether you are new to programming or an experienced developer, this article will provide you with the knowledge you need to reverse a number in Python.

There are several ways to reverse a number in Python. Here are a few examples:

Using While Loop

number = 12345
reverse_number = 0
while number > 0:
   digit = number % 10
   reverse_number = (reverse_number * 10) + digit
   number //= 10
print(reverse_number)

Output

54321

The detailed description of the code is as follows:

  • We first initialize the variables number to 12345 and rev_number to 0.
  • In the first iteration of the while loop, the modulus operator % is used to get the last digit of number, which is 5. The variable digit is set to 5.
  • The reversed number reverse_number is updated by multiplying the current value of reverse_number by 10 and adding the current digit. So, reverse_number becomes 5.
  • The last digit is removed from number by using integer division //, which sets number to 1234.
  • The while loop continues to run until number becomes 0. In the second iteration, digit becomes 4 and reverse_number becomes 54.
  • In the third iteration, digit becomes 3 and reverse_number becomes 543.
  • In the fourth iteration, digit becomes 2 and reverse_number becomes 5432.
  • In the fifth and final iteration, digit becomes 1 and reverse_number becomes 54321.
  • The while loop condition number > 0 is no longer true, so the loop ends.
  • The reversed number reverse_number is printed, which is 54321.
  • So, the output of the program is the reversed number of the original input number 12345, which is 54321.

Let’s dry run the above code to understand step-by-step calculation using the formulas:

Iterationnumrem = num % 10reverse = reverse * 10 + remnum //= 10
11234512345 % 10 = 50 * 10 + 5 = 512345 // 10 = 1234
212341234 % 10 = 45 * 10 + 4 = 541234 // 10 =123
3123123 % 10 = 354 * 10 + 3 = 543123 // 10 = 12
41212% 10 = 2543 * 10 + 2 = 543212 // 10 = 1
511 % 10 = 15432 * 10 + 1 = 54321 (final ans)1 // 10 = 0

Using Slicing

num = 12345
rev_num = str(num)[::-1]
print(int(rev_num))

Output

54321

This code is an example of how to reverse a number in Python using string slicing. Here’s how it works:

  • We first define the variable num and assign it the value 12345.
  • Next, we convert the integer num into a string using the str() function.
  • We use string slicing to reverse the string. The syntax [start:stop:step] is used for string slicing, where start is the starting index (which defaults to 0 if not specified), stop is the stopping index (which defaults to the end of the string if not specified), and step is the step value (which defaults to 1 if not specified). In this case, we leave start and stop blank, and set step to -1, which tells Python to start from the end of the string and move backward. So, [::-1] reverses the string.
  • We assign the reversed string to the variable rev_num.
  • Finally, we convert the reversed string back to an integer using the int() function and print the result.

When we run this code, we get the output 54321, which is the reversed number of the original input number 12345.

Using reversed() Method:

num = input("Enter a number to be reversed: ")
rev_num = int("".join(reversed(num)))
print("The reversed number is:", rev_num)

Output

Enter a number to be reversed: 54321
The reversed number is: 12345

A step-by-step explanation of the above code:

  • The input() function is used to prompt the user to enter a number.
  • The user’s input is stored in the variable num as a string.
  • The reversed() function is applied to the string to create a reversed iterable object containing the characters of the string in reverse order.
  • The join() method is called on an empty string “” to concatenate the characters of the iterable object into a single string.
  • The resulting string, which contains the digits of the input number in reverse order, is converted back to an integer using the int() function.
  • The reversed number is stored in a variable named rev_num.
  • The print() function is used to display the reversed number to the console.

In summary, this code reverses the digits of a given number and prints the result to the console. When executed with the initial value of num set to 12345, it outputs the reversed number 54321.

Using Recursion

def reverse(number):
  if number == 0:
      return 0
  return (number % 10 * (10 ** len(str(number))) // 10) + reverse(number // 10)
   
number = 12345
reverse_number = reverse(number)
print(reverse_number)

Output

54321

Here’s a step-by-step explanation of the code:

  1. A function named reverse is defined that takes a single argument number.
  2. The function first checks if the value of number is equal to 0. If so, it immediately returns 0.
  3. If number is not 0, the function computes the value of the last digit of number by taking the remainder of number divided by 10, using the modulus operator %.
  4. It then computes the length of number by converting it to a string using the str() function and calling the len() function on the resulting string.
  5. The function then computes the reversed number recursively by calling itself with the remaining digits of number (excluding the last digit) as the argument and adding the last digit to the result multiplied by 10 to the power of the length of number minus 1 (to account for the position of the last digit).
  6. Once the recursion has reached the base case (i.e., number equals 0), the function returns the final reversed number.
  7. The variable number is assigned the value 12345.
  8. The function reverse is called with number as its argument, and the resulting reversed number is stored in the variable reverse_number.
  9. The print() function is used to display the reversed number to the console.

Overall, this code reverses the digits of a given number using recursion and prints the result to the console. When executed with the initial value of the number set to 12345, it outputs the reversed number 54321.

Conclusion

In conclusion, reversing a number in Python can be achieved using different techniques. The methods discussed in this article include reversing the number using a while loop, Slicing, the reversed() method to create a reversed iterable object, and implementing a recursive function to reverse the digits of the number. By understanding these methods, programmers can choose the most suitable approach according to their specific needs.

Good Luck with your Learning !!

Related Topics:

Addition of two matrices in Python

How to Draw a Triangle in Python Turtle

What datatype is represented by int in python 3

Coding Spell Python Journey | About Us 

Jerry Richard R
Follow me