How to Reverse a Given Number in Python


1. Introduction

In this example we will show how to reverse a given number, which can be implemented by the method of a while loop statement to reverse each digital of a number.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-

n = int(input("Please input a number: "))
i = 0
while n > 0:
    j = n % 10
    i = i * 10 + j
    n = n // 10
print("The reversed result is: ", i)

Output:

Please input a number: 789456
The reversed result is: 654987

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments