1

I have some code to test other codes that I've written(in ipython notebook).

print_closest = lambda w, wl: print('{}: {} ({})'.format(w, *closest_match(w, wl))) 

This is the code I have and it works on python 3 environment. However, it doesn't work on python 2.7. Instead, it throws an error below.

print_closest = lambda w, wl: print('{}: {} ({})'.format(w, *closest_match(w, wl))) ^ SyntaxError: invalid syntax 

I'd like to make a change on the code above in order to get it work on python2.7 environment as well as python3.

Can anyone please tell me how? Thanks in advance.

2
  • 1
    See: stackoverflow.com/questions/2970858/… Basically it's not supported under python 2.7 Commented Oct 25, 2016 at 17:03
  • Thanks a lot for all the answers replied. I didn't know it was duplicate question. Commented Oct 25, 2016 at 17:12

2 Answers 2

1

In Python 2, print is a statement, not a function (as a function, using it would be an expression). lambdas can consist only of expressions, not full statements.

That said, you can get the Py3 print function on Py2. In modules where you want to switch, add the following as the very first line of code in the file (after any shebang or encoding comments, before everything else):

from __future__ import print_function 

That will make print a function as it is in Py3.

Sign up to request clarification or add additional context in comments.

Comments

1

In Python 2, print is a statement, not a function, and cannot be used in a lambda expression. You can make it work by adding the print_function feature:

from __future__ import print_function print_closest = lambda w, wl: print('{}: {} ({})'.format(w, *closest_match(w, wl))) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.