In this shot, we’ll learn how to use for
loops in Python to generate a left arrow pattern using numbers.
We will use three for
loops: one for the upper, one for the middle, and one for the lower part.
Let’s look at the code below:
# Number of rowsn=6# Upper partfor i in range((n - 1) // 2, 0, -1):for j in range(i):print(" ", end = " ")print(i+1)# Middle partfor i in range(n):print(i+1, end = " ")print()# Lower partfor i in range(1, ((n - 1) // 2) + 1):for j in range(i):print(" ", end = " ")print(i+1)
Line 2: We take the input for the number of rows.
Lines 5 to 8: We create a for
loop to generate the upper portion of the arrow. The outer loop will only run twice because n-1 // 2
will give us 2
(for n = 6
). The inner loop will run j
times to print the spaces and, when it breaks, the outer loop will print i+1
.
Lines 11 to 13: We create another for
loop to generate the middle portion of the arrow. We print i+1
on each iteration. For example, i=0
at the first iteration. When we do i+1
, it is 1
. That is what is printed at the start. Finally, print()
moves the cursor to the next line.
Lines 16 to 20: We create a for
loop to generate the lower portion of the arrow.
Line 18: We use the end
statement to stay on the same line.
Line 19: We use the print()
statement to move to the next line.