0

我想我的问题与全局范围有关。我不确定我不理解的是什么。我在第 6 行的全局范围内定义了 computer_symbol。然后第 18 行的 choose_symbol 函数应该使 computer_symbol 成为用户未选择的任何内容。然后我在第 30 行调用该函数。但是当我尝试使用第 45 行中的变量并测试我的代码时,我看到 computer_symbol 仍然等于仅用作占位符的“无”值。

import random


board_locations = [0, 1, 2, 3, 4, 5, 6, 7, 8]

computer_symbol = 'nothing'

def draw_board():
    print('   |   |   ')
    print(f'_{board_locations[0]}_|_{board_locations[1]}_|_{board_locations[2]}_')
    print('   |   |   ')
    print(f'_{board_locations[3]}_|_{board_locations[4]}_|_{board_locations[5]}_')
    print('   |   |   ')
    print(f' {board_locations[6]} | {board_locations[7]} | {board_locations[8]} ')
    print('   |   |   ')


def choose_symbol(user_symbol):
    if user_symbol == 'X':
        computer_symbol = 'O'
    else:
        computer_symbol = 'X'

    return computer_symbol


draw_board()

user_symbol = input("Would you like to be 'X' or 'O': ")
choose_symbol(user_symbol)

game = True

while game:
    draw_board()

    chosen_location = int(input('Choose the location you want to move on the board: '))
    if chosen_location in board_locations:
        board_locations.pop(chosen_location)
        board_locations.insert(chosen_location, user_symbol)
        draw_board()
        computer_choice = random.choice(board_locations)

        board_locations.pop(computer_choice)
        board_locations.insert(computer_choice, computer_symbol)

起初,我什至没有computer_symbol 变量,因为我认为我可以在函数choose_symbol() 中做到这一点,但程序不喜欢这样,因为尚未定义computer_symbol。

4

2 回答 2

2

您在函数内部使用的computer_symbol变量是函数内部的局部变量,因此它与全局computer_symbol变量不同。global computer_symbol要改变这一点,您可以通过在函数体顶部添加语句来显式引用函数内部的全局变量。

但是,从您显示的代码来看,没有必要让您的函数在此处更改全局变量。一般来说,如果可以的话,最好避免这种副作用。只需删除computer_symbol = 'nothing'分配并分配函数的返回值即可:

computer_symbol = choose_symbol(user_symbol)
于 2021-11-14T20:01:05.500 回答
0

的定义computer_symbol确实是全局的,但是不能在函数内部修改全局变量。为此,您必须添加global var_name,所以它看起来像这样:

def choose_symbol(user_symbol):
    global computer_symbol
    if user_symbol == 'X':
        computer_symbol = 'O'
    else:
        computer_symbol = 'X'
于 2021-11-14T20:00:14.203 回答