Python lambda函数"翻译"导致递归错误

时间:2016-09-11 22:33:56

标签: python lambda

在尝试理解python lambda函数时,我"翻译了#34;这个功能:

s = lambda y: y ** y; s(3)  

进入这个常规的定义函数:

def power_of_self(y):
    return y ** y
power_of_self(3)

当我尝试将其作为脚本运行时(python lambda_stuff.py)我没有问题。但是,当试图通过Python shell运行它时,发生了这种奇怪的事情:

>>> def power_of_self(y):
...     return y ** y
... power_of_self(3)
File "<stdin>", line 3
power_of_self(3)
            ^
SyntaxError: invalid syntax
>>> print power_of_self(3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in power_of_self
File "<stdin>", line 1, in power_of_self
File "<stdin>", line 1, in power_of_self
File "<stdin>", line 1, in power_of_self
**A FEW HUNDRED MORE OF THESE**
RuntimeError: maximum recursion depth exceeded

为什么我的脚本执行与shell执行不同?我想知道...是否与它有任何关系。

2 个答案:

答案 0 :(得分:3)

...表示python shell正在等待更多语句作为函数的一部分。当直接从python shell输入缩进块时,你需要一个空行来结束函数。

>>> def power_of_self(y):
...     return y ** y
...
>>> power_of_self(3)
27

答案 1 :(得分:1)

您的功能仍在shell中定义。在调用函数之前,再点击 Enter