How to generate a right arrow pattern using numbers in Python
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
forloop to iterate through the rows - Inner: A nested
forloop to iterate through the columns
Code
Let’s take a look at the below code snippet.
# Number of rowsn=9# Upper portionu = (n - 1) // 2;# Lower portionl = 3 * n // 2 - 1;for i in range(n):for j in range(n):# Check conditions to print the right arrowif (j - i == u or i + j == l or i == u):print(j+1, end = "")# Otherwise, print spaceelse: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
forloop to iterate through the number of rows. -
Line 11: We create a
forloop 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.jincreases with an increase in the number of rows in the upper half of the arrow.i == u: This prints the middle portion.jincreases in the middle part of the arrow.i + j == l: This prints the lower portion.jdecreases 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.
- We print