我刚开始编程,试图写一些东西,但(当然)失败了。在我找到真正的问题时:UnboundLocalError
。为了把你从废墟中解救出来,我把代码分解为:
def test():
try:
i1 = int(i1)
i2 = int(i2)
except ValueError:
print "you failed in typing a number"
def input():
i1 = raw_input('please type a number \n >')
i2 = raw_input('please type a number \n >')
然后我写下:
^{pr2}$然后我得到:
^{3}$我怎样才能用Python的方式解决这个问题?或者我应该换一种方式吗?在
使用“全局关键字”。在
这导致i1和i2被视为全局变量(在整个程序中可访问),而不是局部变量(只能在中定义它们的函数中访问,这导致了异常)
最标准的方法是为测试方法提供参数:
如果您真的想在交互式提示下进行测试,可以执行以下操作(如@FerdinandBeyer comment中建议的那样):
^{pr2}$然后,一经提示:
相关问题 更多 >
编程相关推荐