此代码的问题在于,如果您首先输入"bob"
以外的任何内容,则当您最终输入"bob"
时,主函数将打印None
。请运行此代码以充分了解我遇到的问题,并为我提供一些答案。
def main(name):
print name
def x():
name = raw_input()
if name == "bob":
return name
else:
print "error"
x()
main(x())
答案 0 :(得分:3)
不要在这里使用递归。一个简单的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()
答案 1 :(得分:0)
您不会在“错误”情况下返回值。将x()
更改为return x()