【发布时间】:2021-06-05 11:29:30
【问题描述】:
需要帮助。我创建了一个空列表来附加名称输入。但是,我不断收到错误“NameError: name 'players' is not defined。如果我将 player = [] 定义为全局变量而不是主函数,它将起作用。仅供参考,我不允许使用全局变量.
def existingPlayers(name):
'''
Check if player name already exists
'''
for player in players:
if player[0].lower() == name.lower():
return True
return False
def getPlayerNames():
'''
Get the names of the players. Check if the number of players and
player names are valid
'''
while True:
name = input("Enter player name or <ENTER> to exit (min 2, max 4 players):")
if len(name) == 0:
if len(players) < 2:
print(f"Minimum 2 players. Currently, {len(players)} player")
continue
else:
break
if existingPlayers(name):
print("Repeated name. Choose another name")
continue
players.append([name])
if len(players) == 4:
break
def main():
players = []
getPlayerNames()
main()
【问题讨论】:
-
你的问题到底是什么?
-
嗯,这些函数仍然可以在一个类中,你可以使用类变量,或者在你的函数中添加另一个参数来接受来自 main 的播放器列表。
-
我的问题是如何附加到我的空列表中,主函数中的玩家 = []
-
你可以使用和定义一个 Players 类吗?这将是避免全局变量的好方法。
-
要么使用类对象,要么让玩家列表成为函数的参数。