如何在python中使用for循环在列表中添加值?

PRK*_*PRK 4 python list python-3.x

我在这里要做的是要求用户输入任何数字,然后要求用户输入任何名称,然后将此输入存储在列表中.

但是,当我输入任何数字时,它只要求输入一次名称并在列表中显示输出:

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()
Run Code Online (Sandbox Code Playgroud)

输出:

Enter number of players: 5
Enter name: Tess
['Tess']
Run Code Online (Sandbox Code Playgroud)

我想要的是,for循环应运行5次,用户输入的5个值存储在列表中.

Ana*_*mar 6

您需要将玩家数量转换为整数然后循环这么多次,您可以使用此range()功能.示例 -

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

    print(tmplist)
Run Code Online (Sandbox Code Playgroud)