谁能告诉我我的功能有什么问题?

时间:2015-04-23 03:25:11

标签: python function

我正在研究这个项目,当代码尝试返回“guess”变量时我不断遇到这个问题,而不是返回“guess”的值,它转到第9行,它将值转换为字符串for某种原因,然后返回。当我在某些东西中使用返回的值时,Python说该值为“NoneType”。

def ask_question(max_length, rowOrCol, guessNumber):
    guess = raw_input("What is the "+rowOrCol+" number of your "+guessNumber+" guess? ")
    try:
        guess = int(guess)
        if guess <= max_length:
            return guess
        else:
            print "That number was too big, it must be no larger then " +str(max_length)
            ask_question(max_length, rowOrCol, guessNumber)
    except(TypeError):
        print "Only numbers are accepted, please try again!"
        ask_question(max_length, rowOrCol, guessNumber)

我用这一行调用函数:

first_guess_row = ask_question(4, "row", "first")

有什么我想念的吗?

3 个答案:

答案 0 :(得分:4)

当然你所有的分支都需要返回......

{{1}}

在你回忆起这个函数之前......但你丢掉了它的返回值

答案 1 :(得分:2)

对于第9行和第12行,您正在进行递归调用。

递归调用是对函数内函数的全新调用。 假设第6行被执行,对ask_question的新调用返回一个值。但它在原始的ask_question调用中返回。

因此您需要更改

ask_question(max_length, rowOrCol, guessNumber)

第9行和第12行

return ask_question(max_length, rowOrCol, guessNumber)

检索该值。

另一个注意事项:递归调用为每次递归使用额外的内存,这可能导致速度减慢甚至崩溃python(如果你递归很多,具体取决于函数的大小)。我建议把你的代码放到这样的循环中:

continue_asking = True
while continue_asking:
    guess = raw_input("What is the "+rowOrCol+" number of your "+guessNumber+" guess? ")
    try:
        # typecheck the guess value
        guess = int(guess)
    except (TypeError):
        print "Only numbers are accepted, please try again!"
        continue

    if guess <= max_length:
        return guess
    else:
        print "That number was too big, it must be no larger then " +str(max_length)

答案 2 :(得分:0)

这是另一种不使用递归函数调用的方法。

def ask_question(max_length, rowOrCol, guessNumber):
    while True:
        try:
            guess = int(raw_input("What is the "+rowOrCol+" number of your "+guessNumber+" guess? "))
            if guess <= max_length:
                return guess
            else:
                print "That number was too big, it must be no larger then " +str(max_length)
        except(ValueError):
            print "Only numbers are accepted, please try again!"
相关问题