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

Python Exercise Example 23

Python Exercise Example 23

Python 100 Examples Python 100 Examples

**Question:** Print the following pattern (a diamond):


   *
  ***
 *****
*******
 *****
  ***
   *

**Analysis:** First treat the pattern as two parts: the first four rows follow one rule and the last three rows follow another. Use nested for loops, with the outer loop controlling rows and the inner loop controlling columns.

Program source code:

Example

#!/usr/bin/python

-- coding: UTF-8 --

from

sys

import

stdout

for

i

in

range

(

4

)

:

for

j

in

range

(

2

i

1

)

:

stdout

.

write

(

'

'

)

for

k

in

range

(

2

i

1

)

:

stdout

.

write

(

'

'

)

print

(

'

'

)

for

i

in

range

(

3

)

:

for

j

in

range

(

i

1

)

:

stdout

.

write

(

'

'

)

for

k

in

range

(

4

2

i

1

)

:

stdout

.

write

(

'

'

)

print

(

'

'

)

Example (Python3)

def

print_diamond

(

rows

)

:

   

Upper half

   

for

i

in

range

(

1

,

rows

,

2

)

:

        spaces

=

" "

(

(

rows - i

)

//

2

)

        stars

=

"*"

       

print

(

spaces + stars

)

   

Lower half

   

for

i

in

range

(

rows

,

0

,

2

)

:

        spaces

=

" "

(

(

rows - i

)

//

2

)

        stars

=

"*"

       

print

(

spaces + stars

)

Set the number of lines; it can be adjusted as needed

rows

=

7

print_diamond

(

rows

)

The output of the above example is:


   *
  ***
 *****
*******
 *****
  ***
   *

Python 100 Examples Python 100 Examples