Python Practice Example 29
Problem:Given a positive integer with no more than 5 digits, the requirements are: First, find how many digits it has; second, print each digit in reverse order.
Program analysis:Learn to decompose each digit.
Program source code:
Example (Python 2.x)
#!/usr/bin/python
# -*- coding: UTF-8 -*-
x = int(raw_input("Please enter a number:\n"))
a = x / 10000
b = x % 10000 / 1000
c = x % 1000 / 100
d = x % 100 / 10
e = x % 10
if a != 0:
print "5 digits:",e,d,c,b,a
elif b != 0:
print "4 digits:",e,d,c,b,
elif c != 0:
print "3 digits:",e,d,c
elif d != 0:
print "2 digits:",e,d
else:
print "1 digit:",e
Example (Python 3.x)
#!/usr/bin/python
x = int(input("Please enter a number:\n"))
a = x // 10000
b = x % 10000 // 1000
c = x % 1000 // 100
d = x % 100 // 10
e = x % 10
if a != 0:
print ("5 digits:",e,d,c,b,a)
elif b != 0:
print ("4 digits:",e,d,c,b)
elif c != 0:
print ("3 digits:",e,d,c)
elif d != 0:
print ("2 digits:",e,d)
else:
print ("1 digit:",e)
The output result of the above example is:
请输入一个数: 23459 5 位数: 9 5 4 3 2
请输入一个数: 3472 4 位数: 2 7 4 3Other extensions
Python 100 Examples