函数内部调用函数会引发错误

时间:2016-11-02 03:17:21

标签: python python-3.x

我正在写一个"你想到一个数字,计算机必须猜测它#34;类型程序。我的代码在这里:http://pastebin.com/6Ny01PJV,每当它从另一个函数调用一个函数时,它就会结束程序或错误。

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)

每当我输入更高的&#39;或者&#39;降低&#39;它结束了程序。

我做错了还是我的代码中有错误,我没有看到?

2 个答案:

答案 0 :(得分:0)

TypeError: 'int' object is not callable表示你已经完成了相同的操作:

def a(x):
    return x+1
a = 1
a(2)

在这里,我们定义了一个名为'a'的函数,然后将'a'重新定义为int,然后尝试调用我们的函数。这不起作用,因为名称'a'不再引用该函数,但现在引用整数1。

看看你的代码,我打赌你会看到类似于上面的内容。

答案 1 :(得分:0)

你一遍又一遍地做同样的错误。我试着解释一下。

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 

现在,正如我所说,你一直有同样的问题。您正在使变量覆盖这些函数。然后,您将这些变量称为函数,就好像您没有覆盖任何内容一样。

因此,TypeError: 'int' object is not callable.某些内容不可调用。

建议:删除global,转而使用return每个函数的值

我看到的另一个问题

reguess = choice(list < guess)

不清楚你期望做什么... list < guess是一个布尔值,你不能random.choice