使用参数从另一个函数调用局部变量,显示错误

时间:2018-03-04 16:34:20

标签: python python-3.x

当我运行这个程序时,我收到了这个错误,如果我把display_board作为参数放在板上,然后用一个像display_board([])

这样的空列表调用它

错误:

Traceback (most recent call last):
  File "C:\Users\withrajat\eclipse-workspace\LCO\tictactoe.py", line 31, in <module>
    player_input()
  File "C:\Users\withrajat\eclipse-workspace\LCO\tictactoe.py", line 29, in player_input
    board.replace("O", marker)
NameError: name 'board' is not defined

代码:

from random import randint
#Step 1: Write a function that can print out a board. Set up your board as a list,
#where each index 1-9 corresponds with a number on a number pad, so you get a 3 by 3 board representation.
def display_board():
    board = []
    for play in range(0,3):
        board.append(["O"]*3)
    for joinBoard in board:
        print(" ".join(joinBoard))



#Step 2: Write a function that can take in a player input and assign their marker as 'X' or 'O'.
#Think about using while loops to continually ask until you get a correct answer.

def player_input():
    print("Type the board in which you want play? 'X' or 'O'")
    marker = str(input(" 'X' or 'O' ")).upper()
    print("You chose {} as a board, now we'll assign it.".format(marker))
    col_random = randint(0,3)
    print(col_random)
    row_random = randint(0,3)
    print(row_random)
    print("\n Now we'll ask you to guess the position of hidden ")
    col_guess= int(input('Guess the colum: >> '))
    row_guess = int(input('Guess the row: >> '))
    while col_guess == col_random and row_guess == row_random:
        display_board().board.replace("O", marker)


player_input()

我的问题是如何在另一个函数中调用该变量,请告诉我如果我将该空列表作为参数传递并删除display_board函数中的board变量,我该怎么办呢?请帮助我,我是编程新手。

1 个答案:

答案 0 :(得分:0)

让我们来看看您怀疑的代码行。

display_board().board.replace("O", marker)

现在,这到底是做什么的?我们可以将此行扩展为某些等效代码,因为您正在跳过几个主要步骤。

printed_board = display_board()
printed_board.replace('O', marker)

根据您上面的代码,display_board不会返回任何内容,因此如果您print(printed_board),您会看到printed_board == NoneNone.board.replace('O', marker)将要投放错误,因为None没有任何属性或功能。

有几种方法可以解决这个问题,我在这里没有明确写出来的评论中所描述的,因为这是一个很好的调试练习,但我绝对会使用全局变量。