Home > Mobile >  How to print an index 0 of a list, with for loop?
How to print an index 0 of a list, with for loop?

Time:05-10

Why does this code, does not return (or print) the 0 index of the list?

N = int(input())

letters = ['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']

for i in range(N):

    print(letters[i]*i)

output: should be:

A
BB
CCC
DDDD
EEEEE
FFFFFF
GGGGGGG

But im getting this, without the "A":

B
CC
DDD
EEEE
FFFFF
GGGGGG

CodePudding user response:

Because i starts counting at zero.

If you type:

for i in range(10):
print(i)

You'll see:

0
1
2
3
4
5
6
7
8
9

If you want to count from 1 to N instead of 0 to N-1, type:

print(letters[i]*(i 1))

CodePudding user response:

Because 0 times a list wont print it. You need to add 1.

N = int(input())

letters = ['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']

for i in range(N):
    print(letters[i]*(i 1))

CodePudding user response:

the i starts from 0. So you need:

for i in range(N):
    print(letters[i]*(i 1))

CodePudding user response:

the for i in range starts at 0. It then tries to execute

print(letters[i]*i)

At index 0, this translates to

print(letters[0]*0)

Since the resulting string is multiplied by zero, it outputs nothing. Changing i to i 1 would solve this issue, as other commenters have pointed out.

  • Related