Python Program to Display Arrow Pattern

1. Introduction

Creating patterns with programming can be both fun and educational. It allows beginners to understand loops and conditional logic in a graphical and intuitive way. In this tutorial, we'll explore how to create an arrow pattern using Python. This simple pattern involves printing a series of asterisks (*) in a specific arrangement to form an arrow shape, demonstrating basic Python programming concepts.

2. Program Steps

1. Define the height of the arrow shaft.

2. Use loops to print the upper part of the arrowhead.

3. Print the shaft of the arrow.

4. Use loops to print the lower part of the arrowhead.

3. Code Program

# User input for the height of the arrow shaft
shaft_height = int(input("Enter the height of the arrow shaft: "))

# Define the width of the arrowhead
arrowhead_width = shaft_height // 2 + 1

# Print the upper part of the arrowhead
for i in range(arrowhead_width):
    print(' ' * (arrowhead_width - i - 1) + '*' * (2 * i + 1))

# Print the shaft of the arrow
for i in range(shaft_height):
    print(' ' * (arrowhead_width - 1) + '*')

# Print the lower part of the arrowhead
for i in range(arrowhead_width - 2, -1, -1):
    print(' ' * (arrowhead_width - i - 1) + '*' * (2 * i + 1))

Output:

Enter the height of the arrow shaft: 5
  *
 ***
*****
  *
  *
  *
  *
  *
*****
 ***
  *

Explanation:

1. The program begins by prompting the user to enter the height of the arrow shaft, storing this value in shaft_height.

2. The arrowhead_width is calculated based on the shaft height to ensure the arrowhead is proportionate. It's set to half the shaft height plus one, to make the arrowhead visually balanced.

3. The upper part of the arrowhead is printed using a loop that decreases the number of leading spaces and increases the number of asterisks as it moves downwards.

4. The shaft of the arrow is printed next. The loop iterates shaft_height times, printing a single asterisk preceded by spaces equal to the arrowhead width minus one, to align it with the center of the arrowhead.

5. The lower part of the arrowhead is printed using a loop similar to the upper part, but in reverse order. It starts with the widest part and narrows down, creating a symmetrical arrowhead.

6. This pattern showcases the use of nested loops, string multiplication for repeating characters, and calculated spacing to create complex shapes. It's a practical demonstration of Python's capabilities for beginners.


Comments