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
ERROR: LoadError: UndefVarError: k not defined
 top-level scope at /workspace/julia/loops.jl:6
 include(::Module, ::String) at ./Base.jl:377
 exec_options(::Base.JLOptions) at ./client.jl:288
 _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.
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