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

Python Exercise Example 29

Python Exercise Example 29

Python 100 Examples Python 100 Examples

**Problem:** Given a positive integer with no more than 5 digits, requirements: 1) find how many digits it has, 2) print its digits in reverse order.

**Program Analysis:** Learn to break down each digit.

Program source code:

Example (Python2.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-digit number:

"

,

e

,

d

,

c

,

b

,

a

elif

b

!=

0

:

print

"

4-digit number:

"

,

e

,

d

,

c

,

b

,

elif

c

!=

0

:

print

"

3-digit number:

"

,

e

,

d

,

c

elif

d

!=

0

:

print

"

2-digit number:

"

,

e

,

d

else

:

print

"

1-digit number:

"

,

e

Example (Python3.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-digit number:

"

,

e

,

d

,

c

,

b

,

a

)

elif

b

!=

0

:

print

(

"

4-digit number:

"

,

e

,

d

,

c

,

b

)

elif

c

!=

0

:

print

(

"

3-digit number:

"

,

e

,

d

,

c

)

elif

d

!=

0

:

print

(

"

2-digit number:

"

,

e

,

d

)

else

:

print

(

"

1-digit number:

"

,

e

)

The output of the above example is:


Please enter a number:
23459
5 位数: 9 5 4 3 2

Please enter a number:
3472
4 位数: 2 7 4 3

Python 100 Examples Python 100 Examples