Diamond

Osama Mohamed
3 min readOct 5, 2023

--

Diamond

The code provided is a Python program to print a diamond shape with the given number of rows.

Then, it uses two nested for loops to iterate over the rows of the diamond, printing spaces and asterisks to create the desired shape.

The first for loop iterates over the rows of the diamond, from bottom to top. For each row, it prints rows - row - 1 spaces, followed by 2 * row + 1 asterisks. The number of spaces ensures that the diamond is centered on the screen, and the number of asterisks ensures that each row of the diamond has one more asterisk than the previous row.

The second for loop iterates over the rows of the diamond, from top to bottom. This loop is almost identical to the first loop, except that it starts at rows - 2 and decrements by 1, instead of starting at 0 and incrementing by 1. This ensures that the diamond is symmetrical, with the same number of rows on the top and bottom.

Here is a breakdown of the code, line by line:

rows = 10

This line declares a variable called rows and sets it to the value 10. This variable will be used to control the size of the diamond.

for row in range(rows):

This line starts a for loop that will iterate over the rows of the diamond. The range() function creates a sequence of numbers from 0 to rows - 1. This ensures that the loop will iterate over all of the rows of the diamond.

print(' ' * (rows - row - 1) + '*' * (2 * row + 1))

This line prints the current row of the diamond. The ' ' * (rows - row - 1) part of the expression prints rows - row - 1 spaces. This ensures that the diamond is centered on the screen. The '*' * (2 * row + 1) part of the expression prints 2 * row + 1 asterisks. This ensures that each row of the diamond has two more asterisks than the previous row.

for row in range(rows - 2, -1, -1):

This line starts a for loop that will iterate over the rows of the diamond, from top to bottom. The range() function creates a sequence of numbers from rows - 2 to -1, decrementing by 1. This ensures that the loop will iterate over all of the rows of the diamond, in reverse order.

print(' ' * (rows - row - 1) + '*' * (2 * row + 1))

This line prints the current row of the diamond. It is almost identical to the print() statement in the first for loop, except that it uses the rows - row - 1 expression to print the correct number of spaces. This ensures that the diamond is symmetrical.

To run the code, you can save it as a Python file (e.g. diamond.py) and then run it in a terminal or command prompt:

python diamond.py

This will print the following output:

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

Here is the source code on GitHub :

Diamond

--

--

No responses yet