# Weird behaviour of variable scope in Julia Loops

**URL:** <https://discourse.julialang.org/t/weird-behaviour-of-variable-scope-in-julia-loops/84359>\
**Category:** General Usage\
**Tags:** question, for-loop\
**Created:** [July 17, 2022, 3:42pm UTC](https://discourse.julialang.org/t/weird-behaviour-of-variable-scope-in-julia-loops/84359 "2022-07-17T15:42:00Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![shwetank\_verma](https://avatars.discourse-cdn.com/v4/letter/s/22d042/32.png) [@shwetank\_verma](https://discourse.julialang.org/u/shwetank_verma)\
**Post date:** [July 17, 2022, 3:42pm UTC](https://discourse.julialang.org/t/weird-behaviour-of-variable-scope-in-julia-loops/84359/1 "2022-07-17T15:42:00Z")

</div>

Hey everyone,  
I have noticed this peculiar behavior of variable scope inside the for loops in Julia. I am calling it peculiar as I have not seen this in Python.

Consider this Python code:

```julia
for i in range(1,10):
    if i == 1:
        print(i)
    else:
        print(x)
    
    x = 2

```

the output of this code is:

```julia
1
2
2
2
2
2
2
2
2

```

However, in Julia this code:

```julia
for i in 1:10
    if i==1
        print(i)
    else
        print(x)
    end

    x = 2
    
end

```

produces an error:  
`UndefVarError: x not defined`

I want to understand why is this like this? I am currently solving this issue by creating a third variable outside the loop.  
I am using Julia 1.7

---

<div class="post-metadata">

**Author:** ![SteffenPL](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/steffenpl/32/206270_2.png) [@SteffenPL](https://discourse.julialang.org/u/SteffenPL)\
**Post date:** [July 17, 2022, 3:49pm UTC](https://discourse.julialang.org/t/weird-behaviour-of-variable-scope-in-julia-loops/84359/2 "2022-07-17T15:49:33Z")

</div>

The problem is that the variable `x` is undefined when the just-in-time (JIT) compiler tries to make sense of the code. For your example it would be enough to define `x` later, but the JIT compiler cannot predict that.

You could for example initialise the variable in an outer scope, e.g. by adding `x = missing` or `x = 0` before the `for` loop.

(A small side note: `range(1,10)` is the same as `1:9`, not `1:10`)
