在 Python 2.7 中的 lambda 函数中使用打印函数时出错 [英] Error using the print function inside a lambda function in Python 2.7
本文介绍了在 Python 2.7 中的 lambda 函数中使用打印函数时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在 Python 2.7 中运行一个简单的代码,但它给了我语法错误.
hello = lambda first: print("Hello", first)
报告的错误是SyntaxError: invalid syntax
.
解决方案
Python 不允许在 lambda 表达式:
<块引用>请注意,使用 lambda 表达式创建的函数不能包含声明或注释.
print
是 Python 2 中的语句,除非您从 __future__
:
I'm running a simple code in Python 2.7, but it is giving me syntax error.
hello = lambda first: print("Hello", first)
The error reported is SyntaxError: invalid syntax
.
解决方案
Python disallows the use of statements in lambda expressions:
Note that functions created with lambda expressions cannot contain statements or annotations.
print
is a statement in Python 2, unless you import the print_function
feature from __future__
:
>>> lambda x: print(x)
File "<stdin>", line 1
lambda x: print(x)
^
SyntaxError: invalid syntax
>>> from __future__ import print_function
>>> lambda x: print(x)
<function <lambda> at 0x7f2ed301d668>
这篇关于在 Python 2.7 中的 lambda 函数中使用打印函数时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文