# Loop doesn't work

**URL:** <https://discourse.julialang.org/t/loop-doesnt-work/64035>\
**Category:** General Usage\
**Tags:** loops\
**Created:** [July 4, 2021, 12:34pm UTC](https://discourse.julialang.org/t/loop-doesnt-work/64035 "2021-07-04T12:34:49Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![shajeenahamed](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/shajeenahamed/32/26789_2.png) [@shajeenahamed](https://discourse.julialang.org/u/shajeenahamed)\
**Post date:** [July 4, 2021, 12:34pm UTC](https://discourse.julialang.org/t/loop-doesnt-work/64035/1 "2021-07-04T12:34:50Z")

</div>

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?

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

```

Error

````julia
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```
````

---

<div class="post-metadata">

**Author:** ![maxfreu](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/maxfreu/32/17468_2.png) [@maxfreu](https://discourse.julialang.org/u/maxfreu)\
**Post date:** [July 4, 2021, 12:50pm UTC](https://discourse.julialang.org/t/loop-doesnt-work/64035/2 "2021-07-04T12:50:47Z")

</div>

k is only defined in the global scope, whereas the loop has its own [scope](https://docs.julialang.org/en/v1/manual/variables-and-scoping/). 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.

---

<div class="post-metadata">

**Author:** ![stevengj](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/stevengj/32/71_2.png) [@stevengj](https://discourse.julialang.org/u/stevengj)\
**Post date:** [July 4, 2021, 12:55pm UTC](https://discourse.julialang.org/t/loop-doesnt-work/64035/3 "2021-07-04T12:55:54Z")

</div>

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](https://discourse.julialang.org/t/another-possible-solution-to-the-global-scope-debacle/15894) and [RFC: bring back v0.6 scope rules in the REPL by JeffBezanson · Pull Request #33864 · JuliaLang/julia · GitHub](https://github.com/JuliaLang/julia/pull/33864)
