TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: Python Program to Reverse a Number
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Python ExamplesPython Tutorials

Python Program to Reverse a Number

Last updated: Nov 23, 2023 11:15 am
By Harsh S.
Share
13 Min Read
Program to Reverse a Number using While Loop, Slicing, and Recursion
SHARE

Reversing numbers is a common task in Python programming. In this tutorial, we will walk you through the steps to create a Python program that reverses a given number. We will explain the process step by step, making it easy for beginners to understand.

Contents
Prerequisites1. While Loop to Reverse a Given Number in PythonWhile Loop Program to Reverse the Digits of a Number in PythonExplanationExample Output2. String Slicing Program to Reverse a Number in PythonExplanationExample Output3. Recursion to Reverse the Digits of a Number in PythonExplanationExample OutputPros and Cons

How to Reverse the Digits of a Number in Python

The reverse operation requires a number to swap the first and last digits, the second and second-to-last digits, and so on. For example, if you have the number 12345, reversing it would result in 54321. You may need to reverse a nondecimal number in various applications, such as checking for palindromes or solving mathematical problems.

Prerequisites

Before you begin, ensure that you have Python installed on your system. You can download and install Python or run it via any of the online Python compilers.

Must Read: 10 Best Python IDEs for Coding

1. While Loop to Reverse a Given Number in Python

The reversing logic in Python is quite simple. You need to extract the digits from the given number and then reverse their order. To make this work, you should try the following six steps:

  1. Initialize a variable to store the reversed number (initially set to 0).
  2. Use a loop to extract the final digit of the input number.
  3. Add the extracted digit to the reversed number, taking into account its position (e.g., if the final digit is 5, add it as the unit place, if it’s 4, add it as the tens place, and so on).
  4. Remove the final digit from the input number.
  5. Repeat steps 2-4 until all digits are extracted and added to the reversed number.
  6. The reversed number is now stored in the variable, and you can print it.

Let’s implement this logic in Python code.

While Loop Program to Reverse the Digits of a Number in Python

# Function to reverse a given number
def rev_num_while_loop(num):
    rev_no = 0

    while num > 0:
        # Extract the final digit
        last_digit = num % 10

        # Add the final digit to the reversed number
        rev_no = (rev_no * 10) + last_digit

        # Remove the final digit from the number
        num = num // 10

    return rev_no 

# User to enter te input
num = int(input("Input a number to reverse: "))

# Call the reverse_number function and store the result
result = rev_num_while_loop(num)

# Display the reversed number
print("The number after the reverse operation:", result)

Also Read: 7 Unique Ways to Reverse a List in Python

Explanation

  1. We define a method rev_num_while_loop(num) that takes an integer num as its parameter. This function will return the reversed number.
  2. We initialize the rev_no variable to 0, which will store the reversed number.
  3. We enter a while loop that continues as long as the input number (num) is greater than 0.
  4. Inside the loop, we use the modulo operator % to extract the final digit of the number, and we store it in the variable last_digit.
  5. We add them last_digit to the rev_no, taking its position into account by multiplying the rev_no by 10 before adding the last_digit. This step ensures that the digits are placed in the correct order when building the reversed number.
  6. We remove the final digit from the input number by using the floor division operator //.
  7. The loop continues until all digits have been extracted and added to the reversed number.
  8. After the loop, we return the rev_no.
  9. We call the input() function for user input, convert it to an integer using int(), and store it in the num variable.
  10. We call the rev_num_while_loop() function with num as the argument and save the output in the result variable.
  11. Finally, we print the reversed number.

Example Output

Let’s see an example of running the program:

Input a number to reverse: 37159
The number after the reverse operation: 95173

Our Pick: String Splitting in Python

2. String Slicing Program to Reverse a Number in Python

String slicing in Python is a unique way to reverse the digits of a number. In this method, we’ll convert the number to a string, reverse the string, and then convert it back to an integer. Here’s how you can do it:

# Function using string slicing
def rev_num_string_slicing(num):
    # Convert the number to a string
    num_str = str(num)

    # Reverse the string using slicing
    reversed_str = num_str[::-1]

    # Convert the reversed string back to an integer
    rev_no = int(reversed_str)

    return rev_no 

# User to enter the input
num = int(input("Input a number to reverse: "))

# Call the reverse_number function and store the result
result = rev_num_string_slicing(num)

# Display the reversed number
print("The number after the reverse operation:", result)

Checkout: Python Remove Last Element from a List

Explanation

  1. We define a method rev_num_string_slicing(num) that takes an integer num as its parameter. This function will return the reversed number.
  2. Inside the function, we first convert the integer num to a string using str(), and we store it in the variable num_str.
  3. We use string slicing with [::-1] to reverse the string. This slicing syntax means to start at the end, move backward by one character at a time, and include all characters. This effectively reverses the string.
  4. After reversing the string, we convert it back to an integer using int() and store it in the variable rev_no.
  5. The function returns the rev_no.
  6. We call the input() function to ask the user to enter a value. Convert it to an integer using int(), and store it in the num variable.
  7. We call the rev_num_string_slicing() function with num as the argument and save the result in the result variable.
  8. Finally, we print the reversed number.

Example Output

Let’s see an example of running the program:

Input a number to reverse: 37159
The number after the reverse operation: 95173

In this Python program, we’ve reversed a number using string slicing. The key idea is to convert the number to a string, reverse the string using slicing, and then convert it back to an integer. This method is a bit more concise than the previous one, and it’s a good alternative if you prefer string manipulation for reversing numbers.

Also Try: Python Get Last Element in a List

3. Recursion to Reverse the Digits of a Number in Python

In order to reverse the digits of a number, we can make use of a recursive function in Python. In this approach, we will define a recursive method that separates the final digit from the rest of the number. It then reverses the number by recursively calling itself. Here’s how you can do it:

# Function using recursion
def rev_num_recursion(num):
    # Base case: If the number has only one digit
    if num < 10:
        return num

    # Extract the final digit
    last_digit = num % 10

    # Recursively reverse the remaining part of the number
    rev_no = rev_num_recursion(num // 10)

    # Construct the reversed number
    return last_digit * 10 ** (len(str(num)) - 1) + rev_no 

# User to enter the input
num = int(input("Input a number to reverse: "))

# Call the reverse_number function and store the result
result = rev_num_recursion(num)

# Display the reversed number
print("The number after the reverse operation:", result)

Explanation

  1. We define a recursive function reverse_number(num) that takes an integer num as its parameter. This function will return the reversed number.
  2. In the base case, we check if the number num is less than 10, which means it has only one digit. In this case, we simply return the number because there’s no need to reverse it further.
  3. If the number has more than one digit, we extract the final digit by taking the modulo % with 10 and store it in the variable last_digit.
  4. We recursively call the reverse_number function with the remaining part of the number by using integer division // to remove the final digit.
  5. In the recursive calls, this process continues until we reach the base case.
  6. When we return from the recursion, we construct the reversed number by multiplying the last_digit by 10, to the power of the number of digits minus 1. This places last_digit at the correct position within the reversed number.
  7. The function returns the rev_no.
  8. After that, call input() to ask for user input. Convert the value to an integer using int(), and store it in the num variable.
  9. We call the reverse_number() function with num as the argument and store the output in the result variable.
  10. Finally, we print the reversed number.

Recommended: Python Append to a Dictionary

Example Output

Let’s see an example of running the program:

Input a number to reverse: 37159
The number after the reverse operation: 95173

In this Python program, we’ve reversed a number using a recursive function. The recursive approach separates the final digit from the remaining part of the number and reverses it by recursively calling the function. This method is a more difficult but nice way to reverse numbers and is useful for understanding recursion in Python.

Pros and Cons

The following table compares the above three ways to reverse the digits of a number in Python:

MethodProsCons
While loopSimple and straightforward to implement.Can be inefficient for large numbers.
String slicingEfficient for all numbers.Requires converting the number to a string.
Recursive functionElegant and concise implementation.Can be inefficient for large numbers due to the overhead of calling the function recursively.

In Python, you need to decide which is the most suitable method for you to reverse a number as per your specific needs. If speed is your concern, then go for string slicing. However, if you want a simple clean code, then use the while loop. The recursive function is the least efficient, but it is good when you want to wrap it with fewer lines of code.

Don’t Miss: Python Sorting a Dictionary

Conclusion

In this tutorial, you learned how to create a Python program to reverse a number. The reverse operation takes the digits out of a number from right to left and builds a new number in reverse sequence. Our example programs used a while loop, string slicing, and recursion to reverse the digits of a number in Python. You can use the code of these sample programs in your tasks as you find necessary.

You Might Also Like

How to Connect to PostgreSQL in Python

Generate Random IP Address (IPv4/IPv6) in Python

Python Remove Elements from a List

Selenium Python Extent Report Guide

10 Python Tricky Coding Exercises

Sign Up For Daily Newsletter

Be keep up! Get the latest breaking news delivered straight to your inbox.
Loading
By signing up, you agree to our Terms of Use and acknowledge the data practices in our Privacy Policy. You may unsubscribe at any time.
Harsh S. Avatar
By Harsh S.
Follow:
Hello, I'm Harsh, I hold a degree in Masters of Computer Applications. I have worked in different IT companies as a development lead on many large-scale projects. My skills include coding in multiple programming languages, application development, unit testing, automation, supporting CI/CD, and doing DevOps. I value Knowledge sharing and want to help others with my tutorials, quizzes, and exercises. I love to read about emerging technologies like AI and Data Science.
Previous Article Java String Format Explained with Examples How to Use Java String Format with Examples
Next Article Programming Language for Android Programming Language for Android in 2024

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x