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

Python Exercise Example 30

Python Exercise Example 30

Python 100 Examples Python 100 Examples

**Problem:** Given a 5-digit number, determine whether it is a palindrome. For example, 12321 is a palindrome: the ones digit equals the ten-thousands digit, and the tens digit equals the thousands digit.

**Analysis:** None.

Program source code:

Example (Python 2.0+)

#!/usr/bin/python

-- coding: UTF-8 --

a

=

int

(

raw_input

(

"

Please enter a number:

\n

"

)

)

x

=

str

(

a

)

flag

=

True

for

i

in

range

(

len

(

x

)

/

2

)

:

if

x

[

i

]

!=

x

[

i

1

]

:

flag

=

False

break

if

flag

:

print

"

%d is a palindrome!

"

%

a

else

:

print

"

%d is not a palindrome!

"

%

a

Example (Python 3.0+)

#!/usr/bin/python3

a

=

int

(

input

(

"

Please enter a number:

\n

"

)

)

x

=

str

(

a

)

flag

=

True

for

i

in

range

(

len

(

x

)

//

2

)

:

if

x

[

i

]

!=

x

[

i

1

]

:

flag

=

False

break

if

flag

:

print

(

"

%d is a palindrome!

"

%

a

)

else

:

print

(

"

%d is not a palindrome!

"

%

a

)

The output of the above example is:


Please enter a number:
12321
12321 是一个回文数!

Python 100 Examples Python 100 Examples