我有这个自称的功能:
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())
现在,如果我只输入“a”或“b”,一切正常:
Type "a" or "b": a
got input: a
但是,如果我输入其他内容然后输入“a”或“b”,我就明白了:
Type "a" or "b": purple
You didn't type "a" or "b". Try again.
Type "a" or "b": a
got input: None
我不知道为什么get_input()
正在返回None
,因为它应该只返回my_var
。这个None
来自哪里以及如何修复我的功能?
答案 0 :(得分:58)
它正在返回None
,因为当你递归调用它时:
if my_var != "a" and my_var != "b":
print('You didn\'t type "a" or "b". Try again.')
get_input()
..你没有返回值。
因此,当递归确实发生时,返回值将被丢弃,然后您将脱离函数的末尾。从函数末尾开始意味着python隐式返回None
,就像这样:
>>> def f(x):
... pass
>>> print(f(20))
None
因此,您需要在get_input()
语句中调用 if
,而不是return
:
if my_var != "a" and my_var != "b":
print('You didn\'t type "a" or "b". Try again.')
return get_input()
答案 1 :(得分:7)
要返回None以外的值,您需要使用return语句。
在您的情况下,if块仅在执行一个分支时执行返回。将返回值移到if / else块之外,或者在两个选项中都返回。
答案 2 :(得分:2)
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.')
return get_input()
else:
return my_var
print('got input:', get_input())
答案 3 :(得分:-1)
我认为这段代码更清楚
def get_workdays(from_date: datetime, to_date: datetime):
# if the start date is on a weekend, forward the date to next Monday
if from_date.weekday() > 4:
from_date = from_date + timedelta(days=7 - from_date.weekday())
# if the end date is on a weekend, rewind the date to the previous Friday
if to_date.weekday() > 4:
to_date = to_date - timedelta(days=to_date.weekday() - 4)
if from_date > to_date:
return 0
# that makes the difference easy, no remainders etc
diff_days = (to_date - from_date).days + 1
weeks = int(diff_days / 7)
return weeks * 5 + (to_date.weekday() - from_date.weekday()) + 1
答案 4 :(得分:-3)
我认为您应该使用 while循环。
if my_var != "a" and my_var != "b":
print('You didn\'t type "a" or "b". Try again.')
get_input()
请考虑输入与" a"不同的内容。和" b"当然,它会调用get_input
,但它会跳过下一部分。这是:
else:
return my_var
并将直接进入:
print('got input:', get_input())
所以,如果你使用while循环:
while my_var!="a" and my_var!="b":
print('You didn\'t type "a" or "b". Try again.')
return get_input()
这种方式我认为你可以处理它。