如何自动创建变量?

时间:2014-01-28 21:22:06

标签: 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")

这就是我得到的:

    >>> 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
    >>> 

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

4 个答案:

答案 0 :(得分:5)

Keep your data out of your variable names;不要在这里使用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)

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

答案 1 :(得分:1)

这是错的,你不应该这样做。但如果你有理由......

而不是exec,修改locals()(vor局部范围变量)或globals()(对于全局范围变量)。

例如:

locals()["a"] = 5
globals()[<value from user>] = 1

答案 2 :(得分:0)

Alvin是列表中的一个元素,如下所示:

 nameList = [`Alvin`, `George` ...]

您应该像这样访问列表中的元素:

 print nameList[0]

答案 3 :(得分:0)

基本上,你有一个字符串列表(字符串是一堆文本)。字符串'Alvin'不是变量Alvin。这是两件不同的事情。如果你想要一个变量,你需要声明一个

alvin = "Alvin"

然后您可以使用print alvin进行打印,但让我们备份您的问题。列表是您可以通过索引访问的集合,例如nameList[0]。 Martijn Pieters的建议很棒,但是如果你不知道字典是什么,那么现在就足够了。