12.07.2015 Views

Is Python a

Is Python a

Is Python a

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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

def Executes at RuntimeThe <strong>Python</strong> def is a true executable statement: when it runs, it creates and assigns anew function object to a name. (Remember, all we have in <strong>Python</strong> is runtime; there isno such thing as a separate compile time.) Because it’s a statement, a def can appearanywhere a statement can—even nested in other statements. For instance, althoughdefs normally are run when the module enclosing them is imported, it’s alsocompletely legal to nest a function def inside an if statement to select between alternativedefinitions:if test:def func( ):...else:def func( ):......func( )# Define func this way# Or else this way# Call the version selected and builtOne way to understand this code is to realize that the def is much like an = statement:it simply assigns a name at runtime. Unlike in compiled languages such as C, <strong>Python</strong>functions do not need to be fully defined before the program runs. More generally,defs are not evaluated until they are reached and run, and the code inside defs is notevaluated until the functions are later called.Because function definition happens at runtime, there’s nothing special about thefunction name. What’s important is the object to which it refers:othername = funcothername( )# Assign function object# Call func againHere, the function was assigned to a different name and called through the newname. Like everything else in <strong>Python</strong>, functions are just objects; they are recordedexplicitly in memory at program execution time.A First Example: Definitions and CallsApart from such runtime concepts (which tend to seem most unique to programmerswith backgrounds in traditional compiled languages), <strong>Python</strong> functions arestraightforward to use. Let’s code a first real example to demonstrate the basics. Asyou’ll see, there are two sides to the function picture: a definition (the def that createsa function), and a call (an expression that tells <strong>Python</strong> to run the function’sbody).A First Example: Definitions and Calls | 303

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

Saved successfully!

Ooh no, something went wrong!