python-3.x – Julia UndefVarError
发布时间:2020-12-20 11:05:36 所属栏目:Python 来源:网络整理
导读:for i in 1:2 if i == 2 print(x) end if i == 1 x = 0 endend UndefVarError : x not defined 为什么代码会给出错误而不是在julia中打印0? 在python中以下代码打印0? for i in range(2): if i==1: print(x) if i==0: x=0 解决方法 原因是因为在循环中,每
for i in 1:2 if i == 2 print(x) end if i == 1 x = 0 end end
为什么代码会给出错误而不是在julia中打印0? 在python中以下代码打印0? for i in range(2): if i==1: print(x) if i==0: x=0 解决方法
原因是因为在循环中,每次执行循环时变量都会获得一个新的绑定,参见
https://docs.julialang.org/en/latest/manual/variables-and-scoping/#For-Loops-and-Comprehensions-1.
事实上,虽然循环改变了Julia 0.6.3和Julia 0.7之间的这种行为(在Julia 0.6.3中没有创建新的绑定).因此以下代码: function f() i=0 while i < 2 i+=1 if i == 2 print(x) end if i == 1 x = 0 end end end 给出以下输出. 朱莉娅0.6.3 julia> function f() i=0 while i < 2 i+=1 if i == 2 print(x) end if i == 1 x = 0 end end end f (generic function with 1 method) julia> f() 0 朱莉娅0.7.0 julia> function f() i=0 while i < 2 i+=1 if i == 2 print(x) end if i == 1 x = 0 end end end f (generic function with 1 method) julia> f() ERROR: UndefVarError: x not defined Stacktrace: [1] f() at .REPL[2]:6 [2] top-level scope For循环在每次迭代时都在Julia 0.6.3中创建了一个新绑定,因此在Julia 0.6.3和Julia 0.7.0下都失败了. 编辑:我已将示例包装在函数中,但如果在全局范围内执行while循环,则会得到相同的结果. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |