for i in 1:2
if i == 2
print(x)
end
if i == 1
x = 0
end
end
UndefVarError:x未定义
为什么代码会给出错误而不是在julia中打印0?
在python中,以下代码打印0?
for i in range(2):
if i==1:
print(x)
if i==0:
x=0
答案 0 :(得分:4)
原因是因为在循环中,每次执行循环时变量都会获得一个新绑定,请参阅https://docs.julialang.org/en/latest/manual/variables-and-scoping/#For-Loops-and-Comprehensions-1。
实际上while
循环在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
提供以下输出。
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
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
循环,则会得到相同的结果。
答案 1 :(得分:2)
忽略我的评论,并使用Bogumil的答案,因为这是你的x
变量在第二次迭代中消失的真正原因。
如果您希望代码像Python一样工作,则可以将global关键字添加到x
的分配中:
for i in 1:2
if i == 2
print(x)
end
if i == 1
global x = 0
end
end
请注意,在大多数情况下不建议这样做,因为它会使您的代码性能受损。 Julia喜欢编译器可以轻松优化的局部变量。