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

前端 未结 1 1215
失恋的感觉
失恋的感觉 2021-01-24 10:25

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 i

相关标签:
1条回答
  • 2021-01-24 10:50

    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>
    
    0 讨论(0)
提交回复
热议问题