title: The rule of thumb as to when we should use a global variable in a function
body: <p></p>When I code games with functions, I often get confused as to which variable to global. <p>I've heard that globalizing variables isn't a very practice, so I try to minimize the amount by not globalizing any, and only globalize the ones that the error message tells me to. But doing that is quite annoying, and it wastes time. </p><strong>Can someone tell me the rule of thumb as to when we should global a variable in a function,<p> and when it is not necessary?</strong> </p>Here is a sample of what I mean (the functions):</p>
  
  <pre><code>import turtle
  from random import randint as rd
  from time import sleep
  delay = 0.1
  
  wn = turtle.Screen()
  wn.setup(400,400)
  wn.tracer(0)
  
  player = turtle.Turtle('square')
  player.penup()
  player.goto(0,-170)
  
  rock = turtle.Turtle('circle')
  rock.shapesize(0.5,0.5)
  rock.penup()
  rock.goto(rd(-190,190),200)
  
  rocks = [rock]
  
  pen = turtle.Turtle(visible=False)
  pen.penup()
  pen.goto(0,150)
  
  def go_left(): # No globalizing here
      if player.xcor() &gt;= -170:
          player.setx(player.xcor()-10)
  
  def go_right(): # No globalizing here
      if player.xcor() &lt;= 170:
          player.setx(player.xcor()+10)
  
  def move_rocks(): # No globalizing here
      for rock in rocks:
          rock.sety(rock.ycor()-rd(0,2))
  
  def loop_rocks():
      global count # rocks not globalized here
      for rock in rocks:
          if rock.ycor() &lt; -200:
              count += 1
              rock.goto(rd(-190,190),200)
  
  def add_rocks():
      global count # rocks not globalized here
      if count == len(rocks) and len(rocks) &lt;= 15:
          rock = turtle.Turtle('circle')
          rock.shapesize(0.5,0.5)
          rock.penup()
          rock.goto(rd(-190,190),200)
          rocks.append(rock)
          count = 0
  
  def write_score():
      global time,score,high_score # pen not globalized here
      time += 1
      if time == 500:
          score += 1
          time = 0
      if score &gt; high_score:
          high_score = score
  
      pen.clear()
      pen.write(f'Score: {score}   High Score: {high_score}',align='center',font=('Arial',10,'bold'))
  
  def hit(): # No globalizing here
      for rock in rocks:
          if player.distance(rock) &lt; 15:
              return True
  
  def die():
      global score,rocks # player not globalized here
      sleep(1)
      for rock in rocks:
          rock.goto(300,300)
      rocks = rocks[:1]
      rocks[0].goto(rd(-190,190),200)
      player.goto(0,-170)
      score = 0
  
  wn.listen()
  wn.onkeypress(go_left,'Left')
  wn.onkeypress(go_right,'Right')
  
  score = 0
  high_score = 0
  count = 0
  time = 0
  
  while True:
      if hit():
          die()
      move_rocks()
      loop_rocks()
      add_rocks()
      write_score()
      wn.update()
  </code></pre>