Python 函数调用函数

Python 函数调用函数,python,function,Python,Function,此代码的问题是,如果您首先输入的不是“bob”,当您最终输入“bob”时,主功能将打印无。请运行此代码以完全理解我遇到的问题,并为我提供一些答案 def main(name): print name def x(): name = raw_input() if name == "bob": return name else: print "error" x() main(x()) 在“error”情况下不返回值

此代码的问题是,如果您首先输入的不是
“bob”
,当您最终输入
“bob”
时,主功能将打印
。请运行此代码以完全理解我遇到的问题,并为我提供一些答案

def main(name):
    print name

def x():
    name = raw_input()
    if name == "bob":
        return name
    else:
        print "error"
        x()

main(x())

在“error”情况下不返回值。将
x()
更改为
return x()

在“error”情况下不返回值。将
x()
更改为
returnx()

此处不要使用递归。一个简单的
while
循环就足够了

def get_name_must_be_bob():
    while True:
        name = raw_input("Enter name: ")
        if name.lower() == "bob":   # "Bob", "BOB" also work...
            return name

        # `else` is not necessary, because the body of the `if` ended in `return`
        # (we can only get here if name is not Bob)

        print "Are you sure you're not Bob? Try again."

def main():
    name = get_name_must_be_bob()
    print "Hello, " + name


if __name__ == '__main__':
    main()

这里不要使用递归。一个简单的
while
循环就足够了

def get_name_must_be_bob():
    while True:
        name = raw_input("Enter name: ")
        if name.lower() == "bob":   # "Bob", "BOB" also work...
            return name

        # `else` is not necessary, because the body of the `if` ended in `return`
        # (we can only get here if name is not Bob)

        print "Are you sure you're not Bob? Try again."

def main():
    name = get_name_must_be_bob()
    print "Hello, " + name


if __name__ == '__main__':
    main()

这是因为在代码中调用
x()
会在未输入
“bob”
时创建递归。首先弹出调用堆栈的函数是您的第一个错误输入(不是
“bob”
),在这种情况下
x
不返回任何内容,或者
None
。我会研究不同的验证方法(使用
while
循环,而不是在这里使用递归),这看起来很混乱。这是因为在代码中调用
x()
会在未输入
“bob”
时创建递归。首先弹出调用堆栈的函数是您的第一个错误输入(不是
“bob”
),在这种情况下
x
不返回任何内容,或者
None
。我会研究不同的验证方法(在这里使用
而不是使用递归),这看起来很混乱。