Error: variable inside a loop

#1

I do not understand why it’s an error:

x = 0
while x < 5
    x += 1
    println(x)
end

I am using Julia 1.1.0 on Windows. This is the error msg:

ERROR: UndefVarError: x not defined
Stacktrace:
 [1] top-level scope at .\REPL[13]:2 [inlined]
 [2] top-level scope at .\none:0

Similar result using for loop:

x = 0
for i = 1:5
    x += 1
    println(x)
end
#2

For what i understand (and is not a lot), there is a problem with the scope of the function, as the variables inside the loop can’t access variables outside the loop (for more information, you can read this discourse thread New Scope Solution ). One way is to directly use the variable using the global prefix:

x = 0
for i = 1:5
    global x += 1
    println(x)
end

But I recommend using directly the iterator:

for i = 1:5
    println(i)
end

If you really need to use that x, you can make a function:

function myfn(x)
for i=1:5    
println(x+i)
end
end

so, you have this

julia> myfn(2)
3
4
5
6
7

if you want the x modified, you can do something like this


function myfn!(x) 
#in julia, the ! means that the function modifies the argument, generally the first one
for i=1:4 # the return statement prints x   
x+=1
println(x)
end
return x
end
julia> x = myfn!(0)
1
2
3
4
5
julia> x
5
#3

For now, I think the easiest thing to do is either (1) stick in Jupyter for these sorts of interactive code, and (2) wrap anything that involves for or while loops in functions (e.g.

function f()
    x = 0
    while x < 5
        x += 1
        println(x)
    end
end
f()
1 Like
#4

It’s worth noting that let will also work just as well:

let x = 0
    while x < 5
        x += 1
    end
    println(x)
end