0

I was writing a small game in which you would guess a number between 0 and 100 in your mind and the computer will try to guess it. Here is a snippet of the code:

import random
global foo
foo=input()
global k
k=random.randint(0,100)

def f():

  if foo.lower()=='too low':
    k=random.randint(k,100)
    foo=input('The number that I guessed is' + ' ' + str(k) +'. Please give your comment.')
    print(k)
f()

It throws an error saying:

UnboundLocalError: local variable ‘foo’ referenced before assignment

Other posts on this site suggest to use global. I did and am still getting an error. Why is Python saying that foo is a local variable even when I have declared it global? And How do I get rid of this bug?

Aaryan Dewan
  • 204
  • 3
  • 11
  • 3
    global has to be used inside the function – PRMoureu Jul 18 '17 at 05:49
  • @PRMoureu , in my previous programs I used it outside the functions and it worked pretty well – Aaryan Dewan Jul 18 '17 at 05:50
  • 1
    @AaryanDewan then you were doing it wrong then, but it didn't matter because you never reassigned to it. If you're only reading from global scope, you don't have to declare it. – Adam Smith Jul 18 '17 at 05:52
  • @AaryanDewan You just think it was working well or you were accidentally creating local variables inside your functions and luckily defined them before using them. – AGN Gazer Jul 18 '17 at 05:53
  • you may have declared global variables outside of the functions that used them [Using global variables in a function other than the one that created them](https://stackoverflow.com/a/423596/1248974), [How do you set a global variable in a function?](http://effbot.org/pyfaq/how-do-you-set-a-global-variable-in-a-function.htm) – chickity china chinese chicken Jul 18 '17 at 05:54

1 Answers1

2

Move global foo from the global scope to inside of the function like this:

import random
foo=input()
k=random.randint(0,100)

def f():
    global foo
    global k
    if foo.lower()=='too low':
        k=random.randint(k,100)
        foo=input('The number that I guessed is' + ' ' + str(k) +'. Please give your comment.')
        print(k)
AGN Gazer
  • 8,025
  • 2
  • 27
  • 45