【问题标题】:NameError: variable is not defined [closed]NameError:变量未定义[关闭]
【发布时间】: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 类吗?这将是避免全局变量的好方法。
  • 要么使用类对象,要么让玩家列表成为函数的参数。

标签: python nameerror


【解决方案1】:

这是你想要的吗?

def existingPlayers(name, players):
    '''
    Check if player name already exists
    '''
    for player in players:
        if player[0].lower() == name.lower():
            return True
    return False

def getPlayerNames(players):
    '''
    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, players):
            print("Repeated name. Choose another name")
            continue
        players.append([name])
        if len(players) == 4:
            break
def main():
    players = []
    getPlayerNames(players)
main()

【讨论】:

  • 它可以工作,但现在代码接受重复的名称,这是不应该的
  • 好的,修复了再测试一下
猜你喜欢
  • 1970-01-01
  • 2022-01-10
  • 2021-08-23
  • 1970-01-01
  • 1970-01-01
  • 2016-12-20
  • 2023-03-05
  • 2020-12-23
相关资源
最近更新 更多