为什么我的函数返回None? [英] Why does my function return None?
问题描述
这可能是一个容易回答的问题,但我无法得到这个简单的程序来工作,这让我发疯。我有这段代码:
def Dat_Function():
my_var = raw_input(Type \a \或\b\:)
如果my_var!=a和my_var!=b:
print您没有输入\ a \或\b \,再试一次。
print
Dat_Function()
else:
print my_var,from Dat_Function
return my_var
def main():
print Dat_Function(),-From main()
main()
现在,如果我只输入a或b,一切都很好。输出是:
$ p $ 输入a或b:a
a -from Dat_Function
a - 从main()
但是,如果我输入其他内容然后输入a或b我得到这个:
输入a或b:紫色
您没有输入a或b。再试一次。
输入a或b:a
a -from Dat_Function
None - 从main()
我不知道为什么 Dat_Function()
正在返回 None
,因为它应该只返回 my_var
。 print语句显示 my_var
是正确的值,但该函数由于某种原因没有返回该值。
<$如果my_var!=a和my_var!=b:
print你没有输入\a \或\b\ 。 再试一次。
Dat_Function()
..你不会返回价值。
因此,当递归发生时,返回值会被丢弃,然后您将从函数的末尾落下。从函数结尾开始,意味着python会隐式地返回 None
,就像这样:
>>> def f(x):
...传递
>>> print(f(20))
None
所以,而不是调用 在您的
,您需要 if
语句中使用Dat Function() return
它。
This may be an easy question to answer, but I can't get this simple program to work and it's driving me crazy. I have this piece of code:
def Dat_Function():
my_var = raw_input("Type \"a\" or \"b\": ")
if my_var != "a" and my_var != "b":
print "You didn't type \"a\" or \"b\". Try again."
print " "
Dat_Function()
else:
print my_var, "-from Dat_Function"
return my_var
def main():
print Dat_Function(), "-From main()"
main()
Now, if I input just "a" or "b",everything is fine. The output is:
Type "a" or "b": a
a -from Dat_Function
a -From main()
But, if I type something else and then "a" or "b", I get this:
Type "a" or "b": purple
You didn't type "a" or "b". Try again.
Type "a" or "b": a
a -from Dat_Function
None -From main()
I don't know why Dat_Function()
is returning None
, since it should only return my_var
. The print statement shows that my_var
is the correct value, but the function doesn't return that value for some reason.
It is returning None
because when you recursively call it:
if my_var != "a" and my_var != "b":
print "You didn't type \"a\" or \"b\". Try again."
print " "
Dat_Function()
..you don't return the value.
So while the recursion does happen, the return value gets discarded, and then you fall off the end of the function. Falling off the end of the function means that python implicitly returns None
, just like this:
>>> def f(x):
... pass
>>> print(f(20))
None
So, instead of just calling Dat Function()
in your if
statement, you need to return
it.
这篇关于为什么我的函数返回None?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!