Python Code Example: right arrow pattern

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.

Code Example

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()

Output

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

Code Explanation

Step-by-Step Breakdown:

Input the Number of Rows

num_rows = int(input("Enter the number of rows: "))
  • The code prompts the user to input the number of rows for the upper half of the pattern.
  • This input is converted to an integer and stored in the variable num_rows.

Generating the Ascending Pattern

for i in range(1, num_rows + 1):
    for j in range(1, i + 1):
        print("*", end="")
    print()
  • The outer loop (for i in range(1, num_rows + 1)) runs from 1 to num_rows inclusive. Each iteration represents a row in the pattern.
  • The inner loop (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.
  • This results in an increasing number of asterisks per row, starting with one asterisk and adding one more on each subsequent row.
Example for Ascending Pattern

If num_rows is 5, the output for this part will be:

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

Generating the Descending Pattern

for i in range(num_rows - 1, 0, -1):
    for j in range(1, i + 1):
        print("*", end="")
    print()
  • The outer loop (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.
  • The inner loop (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.
  • This results in a decreasing number of asterisks per row, starting with num_rows - 1 asterisks and reducing by one on each subsequent row.
Example for Descending Pattern

If num_rows is 5, the output for this part will be:

****
***
**
*
Complete Example Output

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.