Reverse Number Program in Python

Reversing a number in Python: Here, we are going to learn different ways to reverse a given number in Python. By Ankit Rai Last updated : April 09, 2023

Reverse a Number in Python

Reverse number is the number written in the opposite way to the first after performing some mathematical operations.

Reverse Number Example

Take input number from the user and print its reverse.

Input Number:
12345

Output Number:
54321

Different ways to reverse a number in Python

There are two ways that we are implementing here to reverse a number in Python, they are:

  1. Using the simple approach
  2. Using the user-defined function approach

1) Reverse a number using the simple approach

Famous but simple approach for reversing the number: Take input from the user and typecast into an integer, then iterate in the loop till num is not become zero, inside the loop:

  • Find out the remainder.
  • Using this: rev_num = rev_num * 10 + remainder.
  • Update that number by diving by 10.
  • After coming out of the loop printing the reverse number.

Python program to reverse a number using simple approach

if __name__ == "__main__" :

    # take string input from user
    num = int(input('Enter a number: '))

    rev_num = 0

    # iterate the loop till num is not equal to zero
    while(num) :
        rem = num % 10
        rev_num = rev_num* 10 + rem
        num //= 10
    
    print('Reverse number is: ', rev_num)

The output of the above program is:

Enter a number: 12345
Reverse number is:  54321

2) Reverse a number using the user-defined function approach

Make a user-defined function for reversing the Number: Take input from the user and typecast into integer, then call the user-defined function.

Inside the function:

  • Iterate in the loop till num does not become zero:
  • Find out the remainder.
  • Using this: rev_num = rev_num * 10 + remainder.
  • Update that number by diving by 10.
  • After coming out of the loop returning the reverse number to the main.

Python program to reverse a number using user-defined function approach

# define a function for finding 
# reverse of the number
def reverseNum(num) :
    
    rev_num = 0

    # iterate the loop till num is not equal to zero
    while(num) :
        rem = num % 10
        rev_num = rev_num* 10 + rem
        num //= 10

    return rev_num


# Main() method
if __name__ == "__main__" :

    # take string input from user
    num = int(input('Enter a number: '))
    
    print('Reverse number is: ', reverseNum(num))

The output of the above program is:

Enter a number: 12345
Reverse number is:  54321

Python Basic Programs »

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.