我有这段自称的代码:
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正确的值,但函数由于某种原因不返回该值.
我有一个与程序行为改变有关的问题,缺少return语句导致python方法.
下面的count方法打印给定整数中的位数.使用下面的代码块我得到结果为4,这是预期的结果.
def count(x,acc=0):
if x==0:
return acc
return count(x/10,acc+1)
print "Count is %s" %(count(1234))
Run Code Online (Sandbox Code Playgroud)
结果: 计数为4
如果我修改上面的方法,使最后一个语句不包含'return'语句,我得到的结果是'None'.
def count(x,acc=0):
if x==0:
return acc
count(x/10,acc+1)
print "Count is %s" %(count(1234))
Run Code Online (Sandbox Code Playgroud)
结果:计数为无
(我使用的Python版本是:2.7.3)
由于Python不进行尾调用优化或是否涉及任何其他推理,是否会导致上述行为?
perl中的类似代码块(AFAIK不进行尾调用优化)提供了预期的结果,而'return'不是最后一个语句的一部分.
sub counter {
my ($n,$acc) = @_;
return $acc if ($n==0);
counter(int($n/10), $acc+1);
}
print "Count is:" . counter(1234,0) ."\n"
Run Code Online (Sandbox Code Playgroud)
结果:计数为:4
(我在代码块上面运行的Perl版本是:5.14.4和5.8.5).
我的问题是: