Python: Sending the print function as a parameter -


my professor had mentioned it's possible pass functions print parameter, when try , implement syntax error. small missing here?

 def gotime(sequence, action):     element in sequence:        action(element)   def main():     print("testing begins")     test = list ( range( 0 , 20, 2) )      gotime(test, print)     print("testing complete") 

upon running following, receive syntax error:

gotime(test, print)                  ^ syntaxerror: invalid syntax 

if define own function uses print, works, so:

def printy(element):    print(element)  def gotime(sequence, action):    element in sequence:       action(element)  def main():    print("testing begins")    test = list ( range( 0 , 20, 2) )     gotime(test, printy)    print("testing complete") 

in python 3 work out of box. in python 2.7 however, can do:

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

note in python2.7 after from __future__ import print_function won't able use print keyword more:

>>> __future__ import print_function >>> print 'hi'   file "<stdin>", line 1     print 'hi'              ^ syntaxerror: invalid syntax 

although think professor wanted make point functions in python first class citizens (ie: objects) , can passed around other variable. used controversial example though :)

hope helps!


Comments

Popular posts from this blog

php - regexp cyrillic filename not matches -

c# - OpenXML hanging while writing elements -

sql - Select Query has unexpected multiple records (MS Access) -