Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

communitycreator
python
pattern

How to generate a right arrow pattern using numbers in Python

Vinisha Maheshwari

This shot discusses how to generate a right arrow pattern using numbers in Python.

We can generate different patterns using Python once we have a strong grip over the concepts of loops. Here, we simply use for loops to generate a right arrow pattern using numbers.

Description

To execute the same using Python programming, we will use two for loops:

  • Outer: A for loop to iterate through the rows
  • Inner: A nested for loop to iterate through the columns

Code

Let’s take a look at the below code snippet.

# 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):

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


Explanation

  • Line 2: We take the input for the number of rows.

  • Line 5: We assign a variable to create a condition for the upper portion.

  • Line 8: We assign a variable to create a condition for the lower portion.

  • Line 10: We create a for loop to iterate through the number of rows.

  • Line 11: We create a for loop to iterate through the number of columns.

  • Lines 14 to 20: We create the conditions and print the pattern.

    • We print j+1.
    • j - i == u: This prints the upper portion. j increases with an increase in the number of rows in the upper half of the arrow.
    • i == u: This prints the middle portion. j increases in the middle part of the arrow.
    • i + j == l: This prints the lower portion. j decreases with an increase in the number of rows in the lower half of the arrow.
    • We use the end statement to stay on the same line.
    • We use the print() statement to move to the following line.

RELATED TAGS

communitycreator
python
pattern
RELATED COURSES

View all Courses

Keep Exploring