Ryan Ryan - 1 month ago 5
Python Question

Calling function inside of function throws error

I am writing a "you think of a number and the computer has to guess it" type program. My code is here: http://pastebin.com/6Ny01PJV, and whenever it calls a function from another function it either ends the program or errors out.

def guess():
global guess
guess = choice(list)
if guess in cache:
guess()
else:
pass
print (guess)
cache.append(guess)

def check(guess):
global check
check = input("Was " + str(guess) + " the number? (y, n) ").lower()
if check == "n":
global wrong
wrong = input("Lower or higher? ").lower

elif check == "y":
playAgain = input ("I guessed the number! Play again? (y, n)")
if playAgain == "y":
#Right here it will error out with a TypeError
main()
if playAgain == "n":
exit()
else:
print("Please answer in the format 'y' or 'n'"

def reguess():
if wrong == "lower":
reguess = choice(list < guess)
#Here it will end the program, no crash, just no error given
check(reguess)
elif wrong == "higher":
#The same happens here
check(reguess)
reguess = choice(list > guess)


Whenever I type either 'higher' or 'lower', it ends the program.

Am I doing it wrong or is there an error in my code that I am not seeing?

Answer

You keep doing the same error over and over. I'll try to explain.

global list  # already is globally defined on next line 
list = list(range(0,11))  # list() is a function, you overwrite it here 
print (list)

global cache # not necessary, again already global 
cache = []

print ("Write down a number anywhere from 1-10.\nThe computer will try to guess your number.")

def guess():   # this defines a global function 'guess' 
    global guess  # probably gets resolved to the function 
    guess = choice(list)  # you overwrite the 'guess' function 

Now, as I said, you keep having the same problem. You're making your variables overwrite the functions. You're then calling those variables as functions, as if you didn't overwrite anything.

So, TypeError: 'int' object is not callable. or something isn't callable.

Suggestion: remove global in favor of return the value from each function

Another problem I see

reguess = choice(list < guess)

Not clear what you expect that to do... list < guess is a boolean and you can't random.choice that.