Why does this loop have only one iteration instead of the number of iterations entered by the user?

Question:

I am trying to ask the user to enter any number and then ask the user to enter any names, then store this input in a list.

However, when I enter any number, it asks to enter name only one time and shows the output in list:

def main():
    # a = 4
    a = input("Enter number of players: ")
    tmplist = []
    i = 1
    for i in a:
        pl = input("Enter name: " )
        tmplist.append(pl)
        
    print(tmplist)

if __name__== "__main__": 
    main()

output:

Enter number of players: 5
Enter name: Tess
['Tess']

The for loop should run 5 times and user entered 5 values get stored in a list.

Asked By: PRK

||

Answers:

Since the input a is a string
you need to convert it to a number and then use a different for.

it should be

def main():
    #a=4
    a=int(input("Enter number of players: "))
    tmplist=[]
    i=0
    while i < a:
        pl=input("Enter name: ")
        tmplist.append(pl)
        i+=1
    print(tmplist)

main()
Answered By: Srgrn

Since you are using Python3

a=input("Enter number of players: ")

means a is a string “5”. Since this is only one character long – the loop will run just once

You need to use

a = int(input("Enter number of players: "))

You’ll also need to change the loop

for i in range(a):

I recommend using more meaningful variable names – especially if this is homework

def main():
    number_of_players = int(input("Enter number of players: "))
    player_list = []

    for i in range(number_of_players):
        player = input("Enter name: " )
        player_list.append(player)

    print(player_listlist)

if __name__== "__main__": 
    main()
Answered By: John La Rooy

You need to convert the number of players to integer and then loop for that much amount of times, you can use the range() function for this . Example –

def main():
    num=int(input("Enter number of players: "))
    tmplist=[]
    for _ in range(num):
        pl=input("Enter name: " )
        tmplist.append(pl)

    print(tmplist)
Answered By: Anand S Kumar

You got a string a which presumably contained something like '5'. Then you initialize a counter i. Then you loop through this string, which, since it’s '5', resulted in one iteration, because there’s only one character in '5'.

First you have to change it into a number, with a = int(a).

With a as a number, you still can’t loop through that, because a number isn’t an iterable.

So then you should create a range object to loop over, with for i in range(a):.

Then you will be able to carry out your operations as expected.

Answered By: TigerhawkT3
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.