Close Menu
TechBeamersTechBeamers
    TechBeamersTechBeamers
    • Python
    • Java
    • C
    • SQL
    • MySQL
    • Selenium
    • Testing
    • Agile
    • Linux
    • WebDev
    • Technology
    TechBeamersTechBeamers
    Python Examples

    Python Program to Reverse a Number

    By Harsh S.Updated:Nov 23, 2023No Comments9 Mins Read
    Share
    Facebook Twitter LinkedIn Pinterest Email

    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.

    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.
    See also  List Index Method in Python

    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.
    See also  Append Vs. Extend in Python List

    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.
    See also  Floating Point Numbers in Python

    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.

    Previous ArticlePython Sorting a Dictionary
    Next Article 4 Unique Ways to Reverse a String in Python
    Harsh S.

    I'm Harsh, an experienced Software developer with a passion for technology. Specializing in C, Python, Java, Linux, Agile, and more, I love sharing insights through detailed tutorials, quizzes, exercises, and interview questions on various tech topics. Don't miss out on my latest tutorials to level up your skills!

    Add A Comment

    Comments are closed.

    Python Coding Exercises for Beginners
    • 40 Python Exercises for Beginners
    • 6 Python Data Class Exercises
    • 100+ Python Interview Questions for 2024
    • 20 Python Programs to Print Patterns
    Python Basic Tutorials
    • Python Keyword
    • Python Statement
    • Python Comment
    • Python Data Types
    • Python String Methods
    • Python Multiline Strings
    • Python Split Strings
    • Python Slice Strings
    • Iterate Strings in Python
    • Python String Format
    • Python String Concatenation
    • Python Permutations of a String
    • Python Numbers
    • Python List
    • Python List Reverse
    • Python List Slice
    • Python Nested List
    • Python Set
    • Python Tuple
    • Python Dictionary
    • Python Dict to JSON
    • Python Dictionary Examples
    • Python OrderedDict
    • Python Arrays
    • Python Generate SubArrays
    • Python Heapq (Heap queue)
    • Python Operators
    • Python XOR Operator
    • Operator Precedence
    • Python Namespace
    • Python For Loop
    • Python While Loop
    • Python If Else
    • Python Switch Case
    • Python Function
    • Higher Order Functions in Python
    • Python Class
    • Python Class Definition
    • Python Data Class
    • Python Inheritance
    • Python Multiple Inheritance
    • Python Static Method
    • File Handling in Python
    • Python Copy File
    • Python Exception Handling
    • Python Try Except
    • Python Lambda
    • Python Generator
    • Python Module
    Python Pandas in Action
    • Rename Columns using Pandas
    • Python Pandas to Read CSV Files
    • Python Pandas to Merge CSV Files
    • Python Dictionary to DataFrame
    • Python Find Length of List
    Python Important Functions
    • Python Glob()
    • Python Range()
    • Python Float Range()
    • Python Map()
    • Python Filter()
    • Python Enumerate()
    • Python Zip()
    • Python Join()
    • Python Ord()
    Python Advanced Tutorials
    • Python Multithreading
    • Python Socket Programming
    • Selenium Python
    • Python Unittest
    • Python Time Module
    • Python Datetime
    • Python IRC
    • PyLint in Python
    • Python Random Number
    • Python MongoDB
    • Python Pickle
    Python Code Examples
    • Python List Contains Elements
    • Python Search Dictionary by Value
    • Python Check Type of Variable
    • Python Check Version Using Code
    • Python Loop Through Files
    • Compare Strings in Python
    • Replace Strings in Python
    • Size of Integer in Python
    • Simple Socket in Python
    • Threaded Socket in Python
    Python Tips & Tricks
    • 30 Essential Python Tips
    • 10 Python Coding Tips
    • 12 Python Code Optimization Tips
    • 10 Python Programming Mistakes
    Python General Topics
    • Top 10 Python IDEs
    • Top 7 Python Interpreters
    • Top 7 Websites for Python
    • Top 5 Chrome Plugin for Python
    Python Quizzes - General
    • Python Quiz-1
    • Python Quiz-2
    • Python Quiz-3
    • Python Quiz-4
    Python Quizzes - Advanced
    • Python Quiz - Data Structures
    • Python Quiz - Threads
    • Python Quiz - DA
    Python MCQ - Strings
    • Python MCQ Strings-1
    • Python MCQ Strings-2
    Python MCQ - Classes `
    • Python MCQ Classes-1
    • Python MCQ Classes-2
    Python MCQ - Functions
    • Python MCQ Functions-1
    • Python MCQ Functions-2
    Python MCQ - File I/O
    • Python MCQ File I/O-1
    • Python MCQ File I/O-2
    Latest Posts
    • 30 Python Programming Questions On List, Tuple, and Dictionary
    • 4 Different Ways to Rename Columns in Pandas
    • 4 Unique Ways to Reverse a String in Python
    • 40 Google Interview Questions You Need to Join Google in 2023
    • 40 Python Exercises for Beginners
    • 44 Python Data Analyst Interview Questions
    • 7 Websites to Learn Python Programming

    Subscribe to Updates

    Get the latest tutorials from TechBeamers.

    Loading
    • About
    • Contact
    • Disclaimer
    • Privacy Policy
    • Terms of Use
    © 2023 TechBeamers. All Rights Reserved.

    Type above and press Enter to search. Press Esc to cancel.