如何自动创建变量?

use*_*349 2 python variables

我刚刚开始使用python,我目前正在制作一个蛇和梯子游戏.这是我的代码:

    nameList = []
    def players_name():
        x = 0
        input ("""-Press enter to start inputting players' name.
-Press enter after each name inputed to confirm the name to players list.
-After last name inputed, press enter again without any input to finish.""")
        name = input ("Input players' name:")
        while name != "" or len (nameList) <= 1:
            x = x + 1
            if name in nameList:
                print (name,"is already in list, please input a different name.")
                name = input ("")
            elif name =="" and len (nameList) <= 1:
                print ("A minimum of 2 players are require to start the game.")
                name = input ("")
            else:
                nameList.append(name)
                exec("{} = {}".format(name, "1"))
                numList.append("{0}".format (x))
                name = input ("")
        nameList.sort()
        numList.sort()
        print ("There are",len (nameList),"players inputed in your players list!")
        print ("Your players list:",nameList,"\n")
Run Code Online (Sandbox Code Playgroud)

这就是我得到的:

    >>> players_name()
    -Press enter to start inputting players' name.
    -Press enter after each name inputed to confirm the name to players list.
    -After last name inputed, press enter again without any input to finish.
    Input players' name:Alvin
    James
    George

    There are 3 players inputed in your players list!
    Your players list: ['Alvin', 'George', 'James'] 
    >>> print(Alvin)
    Traceback (most recent call last):
      File "<pyshell#1>", line 1, in <module>
        print(Alvin)
    NameError: name 'Alvin' is not defined
    >>> 
Run Code Online (Sandbox Code Playgroud)

我想弄清楚为什么它不宣布"Alvin"作为变量或为什么我不能打印出来.我不确定我是否犯了一个愚蠢的错误.

Mar*_*ers 5

保持数据不受变量名称的影响 ; 不要exec在这里使用,将您的玩家存储在字典中!

players = {}

name = input ("Input players' name:")
while name len(players) < 2:
    x = x + 1

    if name in players:
        print (name,"is already in list, please input a different name.")
        name = input ("")
    elif not name and len(players) < 2:
        print ("A minimum of 2 players are require to start the game.")
        name = input ("")
    else:
        players[name] = 1
        numList.append(str(x))
        name = input ("")

nameList = sorted(players.keys())
print ("There are {} players inputed in your players list!".format(len(nameList)))
print ("Your players list:", nameList)
Run Code Online (Sandbox Code Playgroud)

您的代码仅分配1给每个名称; 我通过1在字典中为每个玩家名称指定值来复制它.您也可以为每个玩家名称存储其他内容,包括您自己的自定义类的实例.