# I get variable not defined error in a trivial example

**URL:** <https://discourse.julialang.org/t/i-get-variable-not-defined-error-in-a-trivial-example/29917>\
**Category:** General Usage\
**Tags:** question\
**Created:** [October 15, 2019, 12:12am UTC](https://discourse.julialang.org/t/i-get-variable-not-defined-error-in-a-trivial-example/29917 "2019-10-15T00:12:35Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![gmouts](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/gmouts/32/9896_2.png) [@gmouts](https://discourse.julialang.org/u/gmouts)\
**Post date:** [October 15, 2019, 12:12am UTC](https://discourse.julialang.org/t/i-get-variable-not-defined-error-in-a-trivial-example/29917/1 "2019-10-15T00:12:35Z")

</div>

So at REPL I typed the following

```julia
julia> using Polynomials

julia> p=Poly([5,-3,-2,-2,1,1])
Poly(5 - 3*x - 2*x^2 - 2*x^3 + x^4 + x^5)

julia> dp=polyder(p)
Poly(-3 - 4*x - 6*x^2 + 4*x^3 + 5*x^4)

julia> function newtonIteration(p,dp,x)
           return x-p(x)/dp(x)
       end
newtonIteration (generic function with 1 method)

julia> x=2
2

julia> x = newtonIteration(p,dp,x)
1.7012987012987013

julia> for i in 1:10
           print(x)
           x = newtonIteration(p,dp,x)
       end
ERROR: UndefVarError: x not defined
Stacktrace:
 [1] top-level scope at .\REPL[7]:2

```

I really don’t understand what has gone wrong here. Does `for` live in a different namespace. What is happening?

By the way, I know that the Newton method has already been implemented, I am just interested at the bug I get in this case.

---

<div class="post-metadata">

**Author:** ![rdeits](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/rdeits/32/286_2.png) [@rdeits](https://discourse.julialang.org/u/rdeits)\
**Post date:** [October 15, 2019, 12:49am UTC](https://discourse.julialang.org/t/i-get-variable-not-defined-error-in-a-trivial-example/29917/2 "2019-10-15T00:49:29Z")

</div>

You can use `global x` inside the loop to declare that you are referring to the global variable `x`, otherwise the `for` loop introduces a new local variable `x`.

But a better solution all around is just to put your code into a function:

```julia
function solve()
  x = newtonIteration(x, ...)
  for i in 1:10 
    x = newtonIteration(x, ...)
  end
end

```

---

<div class="post-metadata">

**Author:** ![gmouts](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/gmouts/32/9896_2.png) [@gmouts](https://discourse.julialang.org/u/gmouts)\
**Post date:** [October 15, 2019, 2:10am UTC](https://discourse.julialang.org/t/i-get-variable-not-defined-error-in-a-trivial-example/29917/3 "2019-10-15T02:10:38Z")

</div>

Oh, I see. This is happening now. It is kind of a pain.

Thanks!
