Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Compute the Reverse of a Number

Python Compute the Reverse of a Number

Document Object Reference Manual Python3 Examples

In this example we will write a Python function that reverses an integer. For example, given the input 123 it outputs 321.

Example

def

reverse_number

(

n

)

:

    reversed_num

=

0

   

while

n

0

:

        digit

=

n %

10

        reversed_num

=

reversed_num *

10

        n

=

n //

10

   

return

reversed_num

Test the function

number

=

12345

print

(

"The reversed number is:"

,

reverse_number

(

number

)

)

Code analysis:

  1. reverse_number The function takes an integer n as its argument.
  2. reversed_num Initialize to 0 to store the reversed number.
  3. while The loop continues while n Continue while it is greater than 0.
  4. In each iteration,digit Obtain the n the last digit of (obtained with n % 10)。
  5. reversed_num is updated to reversed_num * 10 + digit, so that the digit is added to reversed_num end of the
  6. n is updated to n // 10, which removes the n last digit of .
  7. After the loop ends, return reversed_num, that is, the reversed number.

Output result:

反转后的数字是: 54321

Document Object Reference Manual Python3 Examples