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
您需要使用global告诉python您要使用Q的全局值。为此,只需在使用该变量的函数中写入global Q。在
这个问题有很多问题。在
无法验证您在何处定义Q。从引发的错误来看,您可能是在本地范围内定义它。Q将只存在于这个局部作用域中。在
现在看看会发生什么:
您定义Q的方式将返回一个字符串,这将破坏您的代码的其余部分。在
^{2}$尝试以下方法:
相关问题 更多 >
编程相关推荐