# Why do function variables behave differently than global script variables?

**URL:** <https://discourse.julialang.org/t/why-do-function-variables-behave-differently-than-global-script-variables/31028>\
**Category:** New to Julia\
**Tags:** question\
**Created:** [November 13, 2019, 4:28am UTC](https://discourse.julialang.org/t/why-do-function-variables-behave-differently-than-global-script-variables/31028 "2019-11-13T04:28:53Z")\
**Posts on this page:** 1\
**Showing post:** 3

<div class="post-metadata">

**Author:** ![mauro3](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mauro3/32/292_2.png) [@mauro3](https://discourse.julialang.org/u/mauro3)\
**Post date:** [November 13, 2019, 11:02am UTC](https://discourse.julialang.org/t/why-do-function-variables-behave-differently-than-global-script-variables/31028/3 "2019-11-13T11:02:48Z")

</div>

In your first example, `a` inside and outside the loop are different variables; and the `a` outside is a global variable (i.e. defined in global scope, i.e. to top level of a module or at `>>` in the REPL). The rule is:

```nohighlight

    an assignment would result in a modified global variable, or
    a variable is specifically marked with the keyword local.

Thus global variables are only inherited for reading, not for writing

```

[https://docs.julialang.org/en/v1/manual/variables-and-scoping/#Local-Scope-1](https://docs.julialang.org/en/v1/manual/variables-and-scoping/#Local-Scope-1)

Thus because the assignment would “result in a modified global variable” a new local variable is introduced. And because `a += 1` also accesses this new `a` before its assignment it errors.

Example 2 works because you specifically tell Julia to use the global `a`.

Example 3 works because the outer `a` is not a global but also local. Then above rules don’t apply and `a` can be written to.

BTW, this was quite a controversial change late towards stabilizing Julia 1.0, see [Another possible solution to the global scope debacle](https://discourse.julialang.org/t/another-possible-solution-to-the-global-scope-debacle/15894). Also, note that Jupyter notebooks handle this differently, there your example 1 works due to using SoftGlobalScope.jl.

---

_[View the full topic](https://discourse.julialang.org/t/why-do-function-variables-behave-differently-than-global-script-variables/31028)._
