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.

• Arguments, return values, and variables are not declared. As with everything in<strong>Python</strong>, there are no type constraints on functions. In fact, nothing about a functionneeds to be declared ahead of time: you can pass in arguments of any type,return any kind of object, and so on. As one consequence, a single function canoften be applied to a variety of object types—any objects that sport a compatibleinterface (methods and expressions) will do, regardless of their specific type.If some of the preceding words didn’t sink in, don’t worry—we’ll explore all of theseconcepts with real code in this part of the book. Let’s get started by expanding onsome of these ideas and looking at a few examples.def StatementsThe def statement creates a function object and assigns it to a name. Its general formatis as follows:def (arg1, arg2,... argN):As with all compound <strong>Python</strong> statements, def consists of a header line followed by ablock of statements, usually indented (or a simple statement after the colon). Thestatement block becomes the function’s body—that is, the code <strong>Python</strong> executeseach time the function is called.The def header line specifies a function name that is assigned the function object,along with a list of zero or more arguments (sometimes called parameters) in parentheses.The argument names in the header are assigned to the objects passed inparentheses at the point of call.Function bodies often contain a return statement:def (arg1, arg2,... argN):...return The <strong>Python</strong> return statement can show up anywhere in a function body; it ends thefunction call, and sends a result back to the caller. The return statement consists ofan object expression that gives the function’s result. The return statement isoptional; if it’s not present, the function exits when the control flow falls off the endof the function body. Technically, a function without a return statement returns theNone object automatically, but this return value is usually ignored.Functions may also contain yield statements, which are designed to produce a seriesof values over time, but we’ll defer discussion of these until we survey advancedfunction topics in Chapter 17.302 | Chapter 15: Function Basics

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

Saved successfully!

Ooh no, something went wrong!