How to generate a right arrow pattern using alphabets in Python
In this shot, we will discuss how to generate a right arrow pattern using alphabets in Python.
Different patterns can be generated with Python, once you have a strong understanding of loops. We will use simple for loops to generate a right arrow pattern with alphabets.
Description
To execute a right arrow pattern in Python, we will use 2 for loops: an outer for loop to iterate through the rows and an inner nested for loop to iterate through the columns.
Code
Let us 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):ch = chr(65+i)print(ch, 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 the condition for the upper portion of our arrow.
-
Line 8: We assign a variable to create the 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 21: We create conditions and print the pattern.
j - i == u⇒ prints the upper portion.i + j == l⇒ prints the lower portion.i == u⇒ prints the middle portion.ch⇒ creates alphabets from numbers by using the iterative value ofiand the concept of ASCII conversion. We use the starting value65 + (i=0), as the ASCII value ofAis 65.- We use the
endstatement to stay on the same line. - We use the
print()statement to move to the next line.