How to add values ​​to a list using for loop in python?

What I'm trying to do here is to ask the user to enter any number, and then ask the user to enter any names, and then save this entry in the list.

However, when I enter any number, it asks to enter the name only once and displays the output in the 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()

exit:

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

I want the loop to be executed 5 times and the user to enter 5 values ​​that are saved in the list.

+4
source share
4 answers

You need to convert the number of players to an integer, and then cycle over it many times, you can use the function range()to do 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)
+4
source

Python3

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

a - "5". -

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

for i in range(a):

,

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()
+4

a , .

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()
+3

a, - '5'. i. , , '5', , '5' .

, a = int(a).

With aas a number, you still can't skip it because the number is not iterable.

So then you have to create an object rangeto iterate over, s for i in range(a):.

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

+3
source

Source: https://habr.com/ru/post/1612183/


All Articles