|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
在做新版python课程的函数(Ⅱ)课后作业的动手1
ins = ''
def get_ins():
while ins != '3':
ins = input("1/2/3")
get_ins()
报错:
Traceback (most recent call last):
File "D:/PYTHON/py_learn.PY", line 46, in <module>
get_ins()
File "D:/PYTHON/py_learn.PY", line 43, in get_ins
while ins != '3':
UnboundLocalError: local variable 'ins' referenced before assignment
疑问:
我在调用函数之前不是已经赋值了ins吗,为什么调用函数的时候还会报错呢
因为你在函数内部定义了 ins,所以函数内部的 ins 当成了局部变量,而变量不能在定义之前使用,
你在 while 的条件语句中使用了 ins,所以就会报错
你可以加个 global 把 ins 当成全局变量
- ins = ''
- def get_ins():
- global ins # 声明ins为全局变量
- while ins != '3':
- ins = input("1/2/3")
- get_ins()
复制代码
|
|