0
def answer(): 
    if True:
        ans = raw_input('Enter y/n:')

        if ans != "y" and ans != "n":
            print "Try again"
            answer()
        elif ans == "n":
            return False
        elif ans == "y":
            return True
if answer():
    print "It's working!, you entered Y"
else:
    print "You entered N"

When I execute this code, I press Enter several times or enter wrong letters, then I enter y, I always get "You entered N" instead of "It's working!, you entered Y" .

I can't figure out what's the problem, please help me.

4

2 回答 2

9

您正在丢弃if块中函数的返回值。您应该将其更改为:

if ans != "y" and ans != "n":
    print "Try again"
    return answer()

如果您不返回该值,则您的函数将返回None,这将False在外部进行评估ifif True:此外,您的函数内部也不需要。

PS:请避免对这个任务使用递归。您可以通过循环轻松地做到这一点,该while循环会迭代直到用户没有传递正确的输入,并在成功后立即中断。此外,给用户一定次数的尝试以传递正确的输入,以避免无限循环。

于 2013-09-27T14:42:12.540 回答
3

在这种情况下,您实际上不需要递归,只需使用无限循环,如果答案不是“y”或“n”,则不要返回:

def answer(): 
    while True:
        ans = raw_input('Enter y/n:')
        if not ans or ans not in "yn":
            print "Try again"
        else:
            return ans == "y"  # This is more succinct

if answer():
    print "It's working!, you entered Y"
else:
    print "You entered N"
于 2013-09-27T14:45:52.357 回答