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

问题描述 投票:-2回答:1

当我运行这个程序时,我得到了这个错误,如果我把板放在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变量,请告诉我如何才能这样做。请帮助我,我是编程新手。

python python-3.x
1个回答
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没有任何属性或功能。

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

© www.soinside.com 2019 - 2024. All rights reserved.