title: Global variable wrapped in a function
body: <p>I'm learning Julia as part of my PhD in economics but I've come across an issue that doesn't make sense to me. I'm trying to write a function that performs some preliminary calculations then conducts a while loop and returns some value. I want to do this without using global variables. For some reason I can't get it to work. See the minimal working example below which returns a undefined variable error for <code>z</code>. </p>
  
  <pre><code>function test_me(n)
  x = 2 + 1
  y = x - 1 
  i = y
  while i &lt;= n 
      println(i)
      i += 1
      z = 3*i
  end 
  return z 
  end 
  </code></pre>
  
  <p>I can solve the problem easily by making <code>z</code> a global variable. </p>
  
  <pre><code>function test_me2(n)
  x = 2 + 1
  y = x - 1 
  i = y
  while i &lt;= n 
      println(i)
      i += 1
      global z = 3*i
  end 
  return z 
  end 
  </code></pre>
  
  <p>I'm confused as I was under the impression that by wrapping the while loop in a function implies that <code>z</code> is in the local scope and the global declaration is unnecessary. For example the code below works as expected. </p>
  
  <pre><code>function test_me3(n)
  i = 1
  while i &lt;= n 
      println(i)
      i += 1
      z = 3*i
  end 
  return z 
  end
  </code></pre>
  
  <p>I apologise if this issue is trivial. Any help is really appreciated. Thanks. </p>