Python - Reverse a Number

In this program, you will learn how to reverse a number.


Program 1: Reverse a Number using a while loop



    num = int(input('Enter the number: '))
    reversed_num = 0
    
    while num != 0:
        digit = num % 10
        reversed_num = reversed_num * 10 + digit
        num //= 10
    
    print("Reversed number: " + str(reversed_num))

Output



    Enter the number: 1234
    Reversed number: 4321

In this program, the num variable holds the given value and reversed_num is intialized to zero. We are using while loop to reverse a number.

  1. In 1st iteration, the remainder of the num divided by 10 and then it is stored in digit variable. Now, the digit contains the last digit of num. -> digit = 4 Then add this digit to reversed number after multiplying it by 10.

    Note: Multiplication by 10 addes a new place in the reversed number. Oneth place multiplied by 10 give you tenth place, theth gives you hunderedth, and so on.

    In this case, reversed_num contains 0 * 10 + 4 = 4 and num is diivded by 10 so that now it contains 123 (first three digits).

  2. In 2nd iteration, digit equals 3, revresed equals 4 * 10 + 3 = 43 and num = 12.
  3. In 3rd iteration, digit equals 2, reversed equals 43 * 10 +2 = 432 and num = 1.
  4. In 4th iteration, digit equals 1, reversed equals 432 * 10 +1 = 4321 and num = 0.

Now num = 0 . So, the expression num != 0 fails and while loop exits. The reversed_num is already contains values 4321.

Program 2: Reverse a Number using String slicing



    num = int(input('Enter the number: '))

    print("Reversed number: " + str(num)[::-1])
    
    

Output



    Enter the number: 5678
    Reversed number: 8765
    

In this program, we are using string slicing concept to reverse the string. ::-1 represents start:stop:step. When you pass -1 as step, the start point goes to the end and stop at the front.



The following topics can be useful to understand this program.



Related Tutorials