Loop doesn't work

I have just started learning julia, but it kind of stuck in loop. Below code does not work, but syntax seems to be good. any idea?

k = 0
while k < 10
    k += 1
    println(k)
end

Error

ERROR: LoadError: UndefVarError: k not defined
Stacktrace:
 [1] top-level scope at /workspace/julia/loops.jl:6
 [2] include(::Module, ::String) at ./Base.jl:377
 [3] exec_options(::Base.JLOptions) at ./client.jl:288
 [4] _start() at ./client.jl:484
in expression starting at /workspace/julia/loops.jl:5```

k is only defined in the global scope, whereas the loop has its own scope. You can imagine scopes as separate rooms with walls or windows between them. Depending on the situation, you can look from one room into the other. The best solution is to put your code into a function. The worse solution is to put the ‘global’ keyword in front of k inside the loop.

1 Like

Note that you are apparently using an ancient version of Julia (< 1.5). If you upgrade to the latest version (1.6), then (a) your code will work fine in an interactive environment (e.g. the REPL) and (b) in a script it will give a clearer error message. (If you use Jupyter notebooks, then it will work in earlier versions too.)

See also long discussions at Another possible solution to the global scope debacle and RFC: bring back v0.6 scope rules in the REPL by JeffBezanson · Pull Request #33864 · JuliaLang/julia · GitHub

4 Likes