A question about variable scope

I met a problem that make me confused. It is about the scope of variable in Julia.

x = 1
while x <= 10
      x=x+1
      println(x)
end

In this case, julia shows “UndefVarError: x not defined”. Can anyone explain to me why this will happen?

Also, I find that if I change this code like this

x = 1
while x <=10
      global x = x+1
      println(x)
end

This code works but I really don’t want to add a “global” in my code.

This is the (famous) global scope “issue”. You should find a lot about it here on discourse.

Put your code in a function and it works as you want.

2 Likes

Thank you! btw, it this due to Julia language itself? If I update to the latest version, will this global scope “issue” be solve?

No. However, if you use IJulia (Jupyter notebooks), you won’t need to use global. This is because of a settings change for IJulia.

1 Like

thank you!

You can also access this behavior outside of IJulia with the SoftGlobalScope.jl package.

2 Likes

You can, but you probably shouldn’t :wink:

2 Likes