3
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
4

2 回答 2

4

原因是因为在循环中,每次执行循环时,变量都会获得新的绑定,请参阅https://docs.julialang.org/en/latest/manual/variables-and-scoping/#For-Loops-and-理解-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

给出以下输出。

朱莉娅 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-loop 在每次迭代时已经在 J​​ulia 0.6.3 中创建了一个新绑定,因此它在 Julia 0.6.3 和 Julia 0.7.0 下都失败了。

编辑:我已经将示例包装在一个函数中,但是如果您while在全局范围内执行循环,您会得到相同的结果。

于 2018-06-18T16:09:34.843 回答
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 喜欢编译器可以轻松优化掉的局部变量。

于 2018-06-18T16:09:52.663 回答