我有这段自称的代码:
def get_input():
my_var = input('Enter "a" or "b": ')
if my_var != "a" and my_var != "b":
print('You didn\'t type "a" or "b". Try again.')
get_input()
else:
return my_var
print('got input:', get_input())
Run Code Online (Sandbox Code Playgroud)
现在,如果我输入"a"或"b",一切都很好.输出是:
Type "a" or "b": a
got input: a
Run Code Online (Sandbox Code Playgroud)
但是,如果我输入其他内容然后输入"a"或"b",我会得到:
Type "a" or "b": purple
You didn't type "a" or "b". Try again.
Type "a" or "b": a
got input: None
Run Code Online (Sandbox Code Playgroud)
我不知道为什么get_input()
要回来None
,因为它应该只返回my_var
.print语句显示None
正确的值,但函数由于某种原因不返回该值.
我有这段代码,出于某种原因,当我尝试返回路径时,我得到的是:
def get_path(dictionary, rqfile, prefix=[]):
for filename in dictionary.keys():
path = prefix+[filename]
if not isinstance(dictionary[filename], dict):
if rqfile in str(os.path.join(*path)):
return str(os.path.join(*path))
else:
get_path(directory[filename], rqfile, path)
Run Code Online (Sandbox Code Playgroud)
有办法解决这个问题吗?提前致谢.
最近在学习递归,写了一个简单的递归函数来验证我的理解:
def hello(n):
if n == 1:
return 'hello'
else:
print('hello')
hello(n-1)
def returnhello():
return 'hello'
print(returnhello())
print()
print(hello(5))
Run Code Online (Sandbox Code Playgroud)
其输出如下所示:
hello
hello
hello
hello
hello
None
Run Code Online (Sandbox Code Playgroud)
为什么递归中的最后一个调用打印 None 而不是 hello?我期待它打印 5 hello