Python Practice Example 23
Problem:Print the following pattern (diamond):
* *** ***** ******* ***** *** *
Program analysis:First, divide the pattern into two parts: the first four lines follow one rule, and the last three lines follow another rule. Use a double for loop, 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 = "*" * i
print(spaces + stars)
# Lower half
for i in range(rows, 0, -2):
spaces = " " * ((rows - i) // 2)
stars = "*" * i
print(spaces + stars)
# Set the number of rows; can be adjusted as needed.
rows = 7
print_diamond(rows)
# Upper half
for i in range(1, rows, 2):
spaces = " " * ((rows - i) // 2)
stars = "*" * i
print(spaces + stars)
# Lower half
for i in range(rows, 0, -2):
spaces = " " * ((rows - i) // 2)
stars = "*" * i
print(spaces + stars)
# Set the number of rows; can be adjusted as needed.
rows = 7
print_diamond(rows)
The output of the above example is:
* *** ***** ******* ***** *** *Other Extensions
Python 100 Examples