Python中的“变量未定义”错误

2024-06-01 10:10:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我在用Python编写“Reversi”游戏时遇到了一个问题。我希望游戏板的大小是可选的,因此用户可以请求例如4x4或10x10(超过这不是nescesary)。但当我试着给a编码时:


Tags: 用户游戏编码reversinescesary
2条回答

您需要使用global告诉python您要使用Q的全局值。为此,只需在使用该变量的函数中写入global Q。在

这个问题有很多问题。在

无法验证您在何处定义Q。从引发的错误来看,您可能是在本地范围内定义它。Q将只存在于这个局部作用域中。在

现在看看会发生什么:

def foo():
    Q = input("which size of board would you like? for example a 4x4 is a 4")
    print(Q)

foo() 
print(Q)

>> which size of board would you like? for example a 4x4 is a 48
>> 8
>> Traceback (most recent call last):

File "<ipython-input-37-56b566886820>", line 1, in <module>
    runfile('C:/Users/idh/stacktest.py', wdir='C:/Users/idh')

  File "c:\users\idh\appdata\local\continuum\anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 688, in runfile
    execfile(filename, namespace)

  File "c:\users\idh\appdata\local\continuum\anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 101, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "C:/Users/idh/stacktest.py", line 15, in <module>
    print(Q)

NameError: name 'Q' is not defined

您定义Q的方式将返回一个字符串,这将破坏您的代码的其余部分。在

^{2}$

尝试以下方法:

try:
    Q = int(input("Which size of board would you like? For example, a 4x4 board is a 4 \n\n >>"))
except:
    print("Requires an integer between 4 and 10")
    Q = int(input("Which size of board would you like? For example, a 4x4 board is a 4 \n\n >>"))

def whatever_function1(*args, **kwargs):
    whatever it is supposed to do
    return whatever it is supposed to return

def whatever_function2(*args, **kwargs):
    whatever it is supposed to do
    return whatever it is supposed to return

etc

alternatively, you can manually pass Q through to each function after defining it:
Q = int(input("What size would you like?\n")
def getNewBoard(Q):
    # Creates a brand new, blank board data structure.
    board = []
    for i in range(Q):
        board.append([' '] * Q)
    return board

相关问题 更多 >