Variable not defined when incrementing its value in julia

Dear all,
I am trying to increment the value of a variable with this loop:

julia> p=0
0
julia> for i in 1:10
       p += 1
       end
ERROR: UndefVarError: p not defined
Stacktrace:
 [1] top-level scope at ./none:2

I also tried with:

julia> p=Int8
Int8
julia> for i in 1:10
       p += 1
       end
ERROR: UndefVarError: p not defined
Stacktrace:
 [1] top-level scope at ./none:2

Isn’t += the increment operator? Even if I declare the variable as global (which I think is an overkill) the error persists:

julia> global p=0
0
julia> for i in 1:10
       p += 1
       end
ERROR: UndefVarError: p not defined
Stacktrace:
 [1] top-level scope at ./none:2

What am I getting wrong? Thank you.

You need to use global in the local scope where you want to access the global variable p:

julia> p = 0
0

julia> for i in 1:10
           global p += 1
       end

julia> p
10
2 Likes

Yes you are right: global goes inside the loop. I have been trying this right now:

p = 0.0
for j in 1:10
    global p += 1
end
println(p)  # 10.0
for i in 1:10
    global p -= 1
end
println(p) # 0.0 (the same variable has been depleted as expected)
p = -1.0   # new assignment
for i in 1:10
    global p -= 1
end
println(p)   # -11.0 as expected