This Python code generates a diamond-like pattern of asterisks based on user input. It consists of two parts: the first part creates an ascending pattern, and the second part creates a descending pattern.
num_rows = int(input("Enter the number of rows: "))
for i in range(1, num_rows + 1):
for j in range(1, i + 1):
print("*", end="")
print()
for i in range(num_rows - 1, 0, -1):
for j in range(1, i + 1):
print("*", end="")
print()
*
**
***
****
*****
****
***
**
*
num_rows = int(input("Enter the number of rows: "))
num_rows
.for i in range(1, num_rows + 1):
for j in range(1, i + 1):
print("*", end="")
print()
for i in range(1, num_rows + 1)
) runs from 1 to num_rows
inclusive. Each iteration represents a row in the pattern.for j in range(1, i + 1)
) runs from 1 to i
inclusive, determining the number of asterisks to print on the current row.print("*", end="")
prints an asterisk without moving to a new line.print()
moves to the next line after printing all asterisks for the current row.If num_rows
is 5
, the output for this part will be:
*
**
***
****
*****
for i in range(num_rows - 1, 0, -1):
for j in range(1, i + 1):
print("*", end="")
print()
for i in range(num_rows - 1, 0, -1)
) runs from num_rows - 1
down to 1 inclusive. Each iteration represents a row in the pattern.for j in range(1, i + 1)
) runs from 1 to i
inclusive, determining the number of asterisks to print on the current row.print("*", end="")
prints an asterisk without moving to a new line.print()
moves to the next line after printing all asterisks for the current row.num_rows - 1
asterisks and reducing by one on each subsequent row.If num_rows
is 5
, the output for this part will be:
****
***
**
*
When the user inputs 5
for num_rows
, the combined output will be:
*
**
***
****
*****
****
***
**
*
This pattern creates a diamond-like shape with the top half having an increasing number of asterisks and the bottom half having a decreasing number of asterisks.