Computer Science, asked by chandankr3693993, 5 months ago

WAP in python to display the following pattern using nested loop: A B A B A B A B A B A B A B A B A B A B A B A B A​

Answers

Answered by anindyaadhikari13
1

Answer:

This is the required Python program for the question. It works for any number of rows.

n=int(input("Enter the number of rows: "))

x, y=65,1

for i in range(1,n+1):

for j in range(n-i):

print(" ",end="")

for k in range(2*i-1):

print("%c"%(x),end=" ")

x,y=x+y,-y

print()

Explanation:

  • Three loops are created. Outer loop is for printing the rows. Inner loops are for printing the spaces and columns.

  • The outer loop iterates n times where n is the row number so that it can print n rows of the pattern.

  • First inner loop is used for displaying the spaces. After each iteration of this loop, two spaces are added.

  • Second inner loop is used for displaying the characters. We can see that the loop displays the character whose ASCII value is x. ASCII value of 'A' is 65. So, it prints A. Now, value of x is incremented by 1 so as to get character B for the next round of iteration. At the same time, y is multiplied by -1 so as to get the character 'A' back after displaying the character 'B'. So, it goes in an alternate fashion, it prints characters whose ASCII values are 65, 66, 65, 66 and so on.

  • After displaying the pattern for each row, a new line is displayed.

See the attachment for output ☑.

Attachments:
Similar questions