我刚开始与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")
我得到的是:
^{pr2}$我想弄清楚为什么它没有把“Alvin”声明为一个变量,或者为什么我不能把它打印出来。 我不确定我是否犯了一个愚蠢的错误。在
Keep your data out of your variable names;不要在这里使用
exec
,而是将你的播放器存储在字典中!在您的代码只将
1
分配给每个名字;我在这里复制了这一点,在字典中为每个玩家的名字指定了1
。你也可以为每个玩家的名字存储其他东西,包括你自己的自定义类的实例。在这是错误的,你不应该那样做。但如果你有你的理由。。。在
修改}(对于全局作用域变量)。在
exec
而不是exec
(vor局部作用域变量)或{例如:
Alvin
是列表中的一个元素,如下所示:您应该像这样访问列表中的元素:
^{pr2}$相关问题 更多 >
编程相关推荐