Search code examples
pythonlistnested-loops

I am just stuck in python at printing a pattern. Please help me out


I am a beginner in python programming and currently practicing to strong topic 'loop'. A question that say print following pattern. A B C D E F G H I J and so on...

So I done that, but i want to go further much advance level.

Ans.

x = int(input("How much rows you want to print:\n"))
letter = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
k= 0
for row in range(x):
    for col in range(row+1):
        print(letter[k],end=" ")
        k+=1
        if k==len(letter):
            k ==0
    print()

but when i enter 7 or higher number i got an error this.

print(letter[k],end=" ")
list index out of range.

So As per my knowledge it's error because of 'k'. When 'k' reaches len(letter) list was end so I try to fix with if statement that reset value of k to 0 when its reaches len(letter). but I still getting same error. please tell me what I am doing wrong.


Solution

  • The array letter has 26 elements. So you can specify index from 0 to 25. The error you showed is raised when index is bigger than 26.

    To handle index properly, you can implement like this print(letter[k % 26], end= " ")

    % Can calculate the remainder, and numbers above 26 are adjusted to the corresponding numbers below 26

    Please try this one.