Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

communitycreator
python

How to generate a right arrow pattern using asterisks in Python

Vinisha Maheshwari

Overview

In this shot, we’ll learn to generate a right arrow pattern using asterisks in Python. We’ll use simple for loops to generate a right arrow pattern using asterisks.

Description

We’ll use nested for loops. An outer for loop will iterate through the rows, and an inner for loop will iterate through the columns.

Code

Let’s look at the code snippet below:

# Number of Rows
n=9

# Upper Portion
u = (n - 1) // 2;

# Lower Portion
l = 3 * n // 2 - 1;

for i in range(n):
    for j in range(n):

# Checking conditions to print right arrow
        if (j - i == u or i + j == l or i == u):
            print("*", end = "");
        
        # Otherwise print space
        else:
            print(" ", end = "");
    print()

Designing the right arrow asterisk pattern with python

Explanation

  • Line 2: We take the input for the number of rows.
  • Line 5: We assign a value to the variable u, that is, the condition for drawing the upper portion of the right arrow pattern.
  • Line 8: We assign a value to the variable l, that is, the condition for the lower portion of the right arrow pattern.
  • Line 10: We have a for loop to iterate through the number of rows.
  • Line 11: We have a for loop to iterate through the number of columns.
  • Lines 14 to 20: We place the required conditions and print the desired pattern. Following are the rules:
    • j - i == u ⇒ prints the upper portion
    • i + j == l ⇒ prints the lower portion
    • i == u ⇒ prints the middle portion

The end statement is used to stay on the same line. And the print() statement is used to move to the next line.

RELATED TAGS

communitycreator
python
RELATED COURSES

View all Courses

Keep Exploring