python将数据写入文件、总是提示变量未定义_Python中的“变量未定义”错误

这个问题有很多问题。在

无法验证您在何处定义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 "", line 1, in

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值