"变量未定义" Python中的错误

时间:2017-07-27 16:40:33

标签: python

我遇到了编程问题" Reversi" Python中的游戏。我希望游戏板的大小是可选的,因此用户可以请求例如4x4或10x10(超过那个不是必须的)。但是当我尝试编码时:

2 个答案:

答案 0 :(得分:1)

这个问题有很多问题。

无法验证定义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的方式将返回一个字符串,无论如何都将破坏您的其余代码。

Q = int(input("Which size of board would you like?")
for i in range(Q):
    print(i)
>> Traceback (most recent call last):

  File "<ipython-input-39-5abb59a2214a>", line 1, in <module>
    for i in range(Q):

TypeError: 'str' object cannot be interpreted as an integer

尝试以下内容:

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

答案 1 :(得分:0)

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