12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Functions Without returnsIn <strong>Python</strong> functions, return (and yield) statements are optional. When a functiondoesn’t return a value explicitly, the function exits when control falls off the end ofthe function body. Technically, all functions return a value; if you don’t provide areturn statement, your function returns the None object automatically:>>> def proc(x):... print x # No return is a None return...>>> x = proc('testing 123...')testing 123...>>> print xNoneFunctions such as this without a return are <strong>Python</strong>’s equivalent of what are called“procedures” in some languages. They’re usually invoked as statements, and the Noneresults are ignored, as they do their business without computing a useful result.This is worth knowing because <strong>Python</strong> won’t tell you if you try to use the result of afunction that doesn’t return one. For instance, assigning the result of a list appendmethod won’t raise an error, but you’ll get back None, not the modified list:>>> list = [1, 2, 3]>>> list = list.append(4) # append is a "procedure">>> print list # append changes list in-placeNoneAs mentioned in “Common Coding Gotchas” in Chapter 14, such functions do theirbusiness as a side effect, and are usually designed to be run as statements, notexpressions.Enclosing Scope Loop VariablesWe described this gotcha in Chapter 16’s discussion of enclosing function scopes,but, as a reminder, be careful about relying on enclosing function scope lookup forvariables that are changed by enclosing loops—all such references will remember thevalue of the last loop iteration. Use defaults to save loop variable values instead (seeChapter 16 for more details on this topic).Chapter SummaryThis chapter took us on a tour of advanced function-related concepts—lambdaexpression functions; generator functions with yield statements; generator expressions;apply-like call syntax; functional tools such as map, filter, and reduce; andgeneral function design ideas. We also revisited iterators and list comprehensionsChapter Summary | 375

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!