Python Code Example: left arrow pattern

This Python code generates a left arrow pattern of asterisks based on user input. The pattern consists of two parts: an ascending pattern and a descending pattern.

Code Example

# Get the number of rows from the user
num_rows = int(input("Enter the number of rows: "))

# Display the left arrow pattern
for i in range(1, num_rows + 1):
    print(" " * (num_rows - i), end="")
    print("*" * i)

for i in range(num_rows - 1, 0, -1):
    print(" " * (num_rows - i), end="")
    print("*" * i)

Output

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

Code Explanation

Input the Number of Rows

num_rows = int(input("Enter the number of rows: "))
  • The code prompts the user to enter the number of rows for the upper half of the pattern.
  • The 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):
    print(" " * (num_rows - i), end="")
    print("*" * i)
  • Outer Loop:for i in range(1, num_rows + 1)
    • This loop runs from 1 to num_rows inclusive. Each iteration represents a row in the pattern.
  • Printing Spaces:print(" " * (num_rows - i), end="")
    • This line prints a number of spaces determined by (num_rows - i). The number of spaces decreases as i increases, creating the left-aligned effect.
    • The end="" parameter prevents the print function from moving to a new line, allowing the asterisks to be printed on the same line.
  • Printing Asterisks:print("*" * i)
    • This line prints i asterisks. The number of asterisks increases with each row, creating the ascending part of the pattern.
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):
    print(" " * (num_rows - i), end="")
    print("*" * i)
  • Outer Loop:for i in range(num_rows - 1, 0, -1)
    • This loop runs from num_rows - 1 down to 1 inclusive. Each iteration represents a row in the descending pattern.
  • Printing Spaces:print(" " * (num_rows - i), end="")
    • This line prints a number of spaces determined by (num_rows - i). The number of spaces increases as i decreases, maintaining the left-aligned effect.
    • The end="" parameter ensures the asterisks are printed on the same line.
  • Printing Asterisks:print("*" * i)
    • This line prints i asterisks. The number of asterisks decreases with each row, creating the descending part of the pattern.
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 left arrow shape with the top half having an increasing number of asterisks and the bottom half having a decreasing number of asterisks. The spaces ensure the pattern is aligned to the left.