for i in 1:2
if i == 2
print(x)
end
if i == 1
x = 0
end
endUndefVarError :X未定义
为什么代码会给出错误,而不是在julia中打印0呢?
在python中,下面的代码打印0?
for i in range(2):
if i==1:
print(x)
if i==0:
x=0发布于 2018-06-18 16:09:34
原因是,在循环中,每次执行循环时,变量都会获得一个新绑定,请参阅https://docs.julialang.org/en/latest/manual/variables-and-scoping/#For-Loops-and-Comprehensions-1。
实际上,while循环在Julia0.6.3和Julia0.7之间改变了这种行为(在Julia0.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 scopeFor-循环已经在Julia0.6.3中创建了一个新的绑定,因此在Julia 0.6.3和Julia0.7.0下都失败了。
编辑:我已经将示例包装在一个函数中,但是如果在全局范围内执行while循环,则会得到相同的结果。
发布于 2018-06-18 16:09:52
忽略我的评论,继续使用Bogumil的答案,因为这才是x变量在第二次迭代中被拒绝的真正原因。
如果希望代码像在Python中那样工作,可以将全局关键字添加到x的赋值中。
for i in 1:2
if i == 2
print(x)
end
if i == 1
global x = 0
end
end请注意,在大多数情况下不建议这样做,因为这会使您的代码性能受损。Julia喜欢局部变量,编译器可以轻松地优化这些变量。
https://stackoverflow.com/questions/50912829
复制相似问题