This code example is a Python script that prints a diamond shape composed of asterisks (*
).
n = 8
for i in range(1, n):
for j in range(1, i):
print(' ', end='')
for k in range(i, n):
print("* ", end='')
print()
for i in range(n - 1, 0, -1):
for j in range(1, i):
print(' ', end='')
for k in range(i, n):
print("* ", end='')
print()
* * * * * * *
* * * * * *
* * * * *
* * * *
* * *
* *
*
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
n
n = 8
This sets the height of the diamond. The diamond will have n-1
rows in the upper part and n-1
rows in the lower part, for a total height of 2*(n-1)
.
for i in range(1, n):
for j in range(1, i):
print(' ', end='')
for k in range(i, n):
print("* ", end='')
print()
for i in range(1, n):
iterates i
from 1 to n-1
.for j in range(1, i):
prints spaces before the asterisks, increasing the number of spaces as i
increases.for k in range(i, n):
prints the asterisks. The number of asterisks decreases as i
increases.print()
moves to the next line after each row.The upper part of the diamond is generated by decreasing the number of asterisks and increasing the number of leading spaces with each row.
for i in range(n - 1, 0, -1):
for j in range(1, i):
print(' ', end='')
for k in range(i, n):
print("* ", end='')
print()
for i in range(n - 1, 0, -1):
iterates i
from n-1
down to 1.for j in range(1, i):
prints spaces before the asterisks, decreasing the number of spaces as i
decreases.for k in range(i, n):
prints the asterisks. The number of asterisks increases as i
decreases.print()
moves to the next line after each row.The lower part of the diamond is generated by increasing the number of asterisks and decreasing the number of leading spaces with each row.
n-1
asterisks and reduces down to 1 asterisk, shifting right by one space in each row.n-1
asterisks, shifting left by one space in each row.