Python: Sending the print function as a parameter

python

Solution

In Python 3 that will work out of the box. In Python 2.7 however, you can do:

from __future__ import print_function
def foo(f,a):
    f(a)

foo(print,2)
2

Note that in Python2.7 after you do `from __future__ import print_function` you won't be able to use `print` like a keyword any more:

>>> from __future__ import print_function
>>> print 'hi'
  File "<stdin>", line 1
    print 'hi'
             ^
SyntaxError: invalid syntax

Although I think your professor only wanted to make a point that functions in Python are first class citizens (ie: objects) and they can be passed around as any other variable. He used a controversial example though :)

Hope this helps!

Problem

My professor had mentioned that it's possible to pass functions like print as a parameter, but when I try and actually implement it I get a syntax error. Is it something small that I am missing here? ``` def goTime(sequence, action): for element in sequence: action(element) def main(): print("Testing Begins") test = list ( range( 0 , 20, 2) ) goTime(test, print) print("Testing Complete") ``` Upon running the following, I receive this syntax error: ``` goTime(test, print) ^ SyntaxError: invalid syntax ``` If I define my own function that uses print, it works, like so: ``` def printy(element): print(element) def goTime(sequence, action): for element in sequence: action(element) def main(): print("Testing Begins") test = list ( range( 0 , 20, 2) ) goTime(test, printy) print("Testing Complete") ```

Original source

Related problems