是否有充分的理由说明为什么在函数中只有一个return语句是更好的做法?
或者,一旦逻辑正确就可以从函数返回,这意味着函数中可能有很多返回语句?
我有以下代码失败,出现以下错误:
RuntimeError:超出最大递归深度
我试图重写它以允许尾递归优化(TCO).我相信如果发生TCO,这段代码应该是成功的.
def trisum(n, csum):
if n == 0:
return csum
else:
return trisum(n - 1, csum + n)
print(trisum(1000, 0))
Run Code Online (Sandbox Code Playgroud)
我是否应该断定Python不执行任何类型的TCO,或者我只是需要以不同的方式定义它?
我有这段自称的代码:
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).
我的问题是:
以下代码返回None某些值(例如306, 136),对某些值(42, 84),它会正确返回答案.在print a和return a应产生相同的结果,但它并不:
def gcdIter (a,b):
c = min (a,b)
d = max (a,b)
a = c
b = d
if (b%a) == 0:
print a
return a
gcdIter (a,b%a)
print gcdIter (a,b)
Run Code Online (Sandbox Code Playgroud)