【问题标题】:Why am I not changing the global scope the way I thought为什么我没有像我想的那样改变全局范围
【发布时间】:2021-11-14 19:48:06
【问题描述】:

我想我的问题与全局范围有关。我不确定我不理解的是什么。我在第 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。

【问题讨论】:

    标签: python tic-tac-toe global-scope


    【解决方案1】:

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

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

    computer_symbol = choose_symbol(user_symbol)
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-04-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-07
        相关资源
        最近更新 更多