简体   繁体   中英

Error using the print function inside a lambda function in Python 2.7

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM