How to generate a right arrow pattern using asterisks in Python
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 Rowsn=9# Upper Portionu = (n - 1) // 2;# Lower Portionl = 3 * n // 2 - 1;for i in range(n):for j in range(n):# Checking conditions to print right arrowif (j - i == u or i + j == l or i == u):print("*", end = "");# Otherwise print spaceelse:print(" ", end = "");print()
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
forloop to iterate through the number of rows.
- Line 11: We have a
forloop 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 portioni + j == l⇒ prints the lower portioni == 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.