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.
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.
Let us 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): ch = chr(65+i) print(ch, end = " "); # Otherwise print space else: print(" ", end = " "); print()
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
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 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 of
iand the concept of ASCII conversion. We use the starting value
65 + (i=0), as the ASCII value of
endstatement to stay on the same line.
print()statement to move to the next line.
View all Courses