Numerous patterns can be printed in Python once we have a strong grip over loops. Here we’ll use simple for
loops to generate a butterfly pattern using letters of the English alphabet.
To execute a butterfly pattern in Python, we’ll use 2 for
loops: one for the upper half and the other for the lower half.
Let’s look at the code below.
# Number of rowsr = 5# Upper Trianglesfor i in range(1, r+1):ch = chr(64+i)print(ch*i, end="")print(" "*(r-i)*2, end="")print(ch*i)# Lower Trianglesfor i in range(r,0,-1):ch = chr(64+i)print(ch*i, end="")print(" "*(r-i)*2, end="")print(ch*i)
Line 2: We take the input for half the number of rows (which is half the length of the wings of the butterfly).
Lines 5–9: We create a for
loop to generate the upper triangles.
ch
is used to create letters from numbers by using the iterative value of i
and the concept of ASCII conversion. The starting value 64+(i=1)
has been used as ASCII value of A
, which is 65.Lines 12 to 16: We create a for
loop to generate the lower triangles.
ch
is used to create alphabets from numbers by using the iterative value of i
and the concept of ASCII conversion. The starting value 64+(i=1)
has been used as ASCII value of A
, which is 65.Free Resources