尝试从函数分配时,全局变量不起作用

问题描述

我正在学习Python,但我在使用gobal变量时遇到问题。我已经全局定义了变量,然后使用global关键字从函数分配它们。但仍然,当它运行脚本时,它无法分配变量。

看着这个解决方Using global variables in a function,我不知道他的代码为什么起作用,而我的相同逻辑却失败了。数小时无法弄清并停留在小问题上。

def player_input():
    player_1_name = input('Please enter your name Player 1.')
    player_2_name = input('Please enter your name Player 2.')
    player_1_symbol='None'
    player_2_symbol=''
    allowed_symbol=['X','O']
    symbol_accepted = False

def get_symbol():
    global player_1_symbol
    player_1_symbol = input('Please enter your preferred symbol {}. It can be either X or O.   '.format(player_1_name))
    print('value of symbol after assignment: '+ player_1_symbol)

def validate_symbol():
    global symbol_accepted
    print('value of symbol when process started: '+ player_1_symbol)
    if player_1_symbol.upper() in allowed_symbol:
        print('it passed')
        symbol_accepted = True
    else:
        print('it came here,because it did not find the value of player_1_symbol')
        get_symbol()

while symbol_accepted == False:
    validate_symbol()

if player_1_symbol.upper() == 'O':
    player_2_symbol = 'X'
else:
    player_2_symbol = 'O'

print("{},unfortunately you don't have choice. You have been assigned the symbol {}.".format(player_2_name,player_2_symbol))

我要实现的结果是我想assign player_1_symbol从get_symbol函数获取全局变量symbol_accepted也是如此。没有变量被分配。我正在打印它们,但我不能仅仅理解为什么它不起作用。我在youtube上看了几个视频和一些文章

我还看了一些其他有关输入验证的视频/文章,但是一旦开始,我想了解它的问题,以便将来可以与global一起使用。

解决方法

我创建了一个带有player_symbols的数组(player_1为0,player_2为1),因此可以正确分配变量。我还修复了一个错误,该错误重复了validate_symbol,因为symbol_accepted具有相同的错误。

def player_input():
    player_1_name = input('Please enter your name Player 1.')
    player_2_name = input('Please enter your name Player 2.')
    player_symbols = ["",""]
    allowed_symbol = ['X','O']
    symbol_accepted = False

    def get_symbol():
        player_symbols[0] = input(
            'Please enter your preferred symbol {}. It can be either X or O.   '.format(player_1_name))
        print('value of symbol after assignment: ' + player_symbols[0])

    def validate_symbol(symbol_accepted):
        print('value of symbol when process started: ' + player_symbols[0])
        if player_symbols[0].upper() in allowed_symbol:
            print('it passed')
            symbol_accepted = True
        else:
            print('it came here,because it did not find the value of player_1_symbol')
            get_symbol()
        return symbol_accepted

    while symbol_accepted == False:
        symbol_accepted = validate_symbol(symbol_accepted)

    if player_symbols[0].upper() == 'O':
        player_symbols[1] = 'X'
    else:
        player_symbols[1] = 'O'

    print("{},unfortunately you don't have choice. You have been assigned the symbol {}.".format(player_2_name,player_symbols[1]))
player_input()