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.

Chapter 15CHAPTER 15Function Basics15In Part III, we looked at basic procedural statements in <strong>Python</strong>. Here, we’ll move onto explore a set of additional statements that we can use to create functions of ourown.In simple terms, a function is a device that groups a set of statements so they can berun more than once in a program. Functions also can compute a result value and letus specify parameters that serve as function inputs, which may differ each time thecode is run. Coding an operation as a function makes it a generally useful tool, whichwe can use in a variety of contexts.More fundamentally, functions are the alternative to programming by cutting andpasting—rather than having multiple redundant copies of an operation’s code, wecan factor it into a single function. In so doing, we reduce our future work radically:if the operation must be changed later, we only have one copy to update, not many.Functions are the most basic program structure <strong>Python</strong> provides for maximizing codereuse and minimizing code redundancy. As we’ll see, functions are also a design toolthat lets us split complex systems into manageable parts. Table 15-1 summarizes theprimary function-related tools we’ll study in this part of the book.Table 15-1. Function-related statements and expressionsStatementCallsdef, return, yieldExamplesmyfunc("spam", "eggs", meat=ham)def adder(a, b=1, *c):return a+b+c[0]global def changer( ):global x; x = 'new'lambdaFuncs = [lambda x: x**2, lambda x: x*3]299

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

Saved successfully!

Ooh no, something went wrong!