有人能告诉我为什么这个带raw_input的递归方法没有返回?

时间:2016-03-28 21:00:06

标签: python if-statement recursion

以下是声明:

def recursive(y):
    if y < 10:
        return y
    else:
        z = raw_input("Please enter a number: ")
        recursive(z)

x = raw_input("Please enter a number: ")
t = recursive(x)

print t

每当我运行它时,如果我输入一个等于或大于10的数字,它会提示我再次输入一个数字。如果我输入一个小于10的数字,它仍然告诉我输入一个数字;但是,如果我输入少于10,if y < 10不应该是真的,它会返回那个数字吗?

2 个答案:

答案 0 :(得分:0)

你有两个问题:

  • 您不会返回通话结果
  • 您不会将raw_input(字符串)转换为int。

以下是更正后的版本:

def recursive(y):
    if y < 10:
        return y
    else:
        z = raw_input("Please enter a number: ")
        return recursive(int(z))

答案 1 :(得分:-1)

一如既往,因为你没有在你的分支中返回......

def recursive(y):
    if float(y) < 10: # also you need to make this a number
        return y
    else:
        z = raw_input("Please enter a number: ")
        return recursive(z) #this is almost always the problem with these questions