A very simple question about for loop in julia

I have the following very simple codes (Julia 1.5.0):

#test_for.jl

a = 100
for i=1:10
a = a+1
end
b = a
println("a=",a," b=",b) # I want to get a =110 and b=110

When I executed the script, julia says variable ‘a’ is not defined. I searched on the Internet and quite stunned to find out that the variables inside “for” are local variables. So, can anyone provide any solutions that can realize the above code in Julia? Thanks!

The key point is that I cannot understand why the variables inside “for” are defined as “local”, since I didn’t use a function in this case. (LOL…)

I also found out some similar topics, but the focus are different:

Since you’re running it in a script, and not immediately in the repl, it should behave in the >=1.5 way, assigning a local variable and giving a warning.

https://docs.julialang.org/en/v1/manual/variables-and-scoping/#On-Soft-Scope

As for solution, make it global a = a+1

1 Like

So in

global a = a+1

Julia knows ‘a’ at the right of the expression is a global variable, right? This is my understanding, the only problem is that when we use the same variable at the left of the expression inside ‘for’ loop, the conflicts appear.

Yes. Since there is no other a to be found.

1 Like