Python:如何从用户获取多个值?

时间:2018-05-11 06:49:21

标签: python

我在python中制作一个单词链游戏,但我被困在一个地方。 我想做的是

The game begins by asking how many people wish to play, and then prompting you to enter a name
for each of the players.

为此,我创建了一个代码

def inputWord():
    Players = str(input("Enter Number of Players:"))
    Name = []
    WordChain = 0
    ls = list()
    PlayerNames = {}
    for i in range(0, int(Players)):
        Name = input("Enter Player Name:")
        PlayerNames = ls.append(Name)
        print(PlayerNames)
    print(PlayerNames)  

inputWord()

the Output that I am getting is 
Enter Number of Players:2
Enter Player Name:David
None
Enter Player Name:Martin
None
None

相反,我需要这个

Enter Number of Players:2
Enter Player Name:David
David
Enter Player Name:Martin
Martin
[David, Martin] #list of the names for later use

我是python的新手,请帮助我。

1 个答案:

答案 0 :(得分:1)

append是一个python列表方法,用于将新值附加到现有列表。该方法不返回任何内容。当您使用时:

PlayerNames = ls.append(Name)

您从用户那里获得的Name会附加到您的列表中,但它不会返回任何内容。但是您试图将返回值分配给PlayerNames变量,在这种情况下,变量将为空。因此,每当您尝试打印PlayerNames时,它都会显示None。相反,您已在Name变量中拥有用户名,您可以使用print(Name)在屏幕上打印用户名。

你的循环应该是这样的:

for i in range(0, int(Players)):
    Name = input("Enter Player Name:")
    ls.append(Name)      <-- append user's name to your list.
    print(Name)          <-- show what user has entered.
print(ls)                <-- print the whole list after the loop.

您应该阅读有关python数据结构的更多信息。它有很好的文档。

https://docs.python.org/2/tutorial/datastructures.html