Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 50

Function Basics

Coding Functions
• def is executable code.
• def creates an object and assigns it to a name.
• lambda creates an object but returns it as a result.
• return sends a result object back to the caller.
• yield sends a result object back to the caller, but
remembers where it left off.
• global declares module-level variables that are to be
assigned.
• nonlocal declares enclosing function variables that are to
be assigned.
• Arguments are passed by assignment (object reference).
• Arguments are passed by position, unless you say
otherwise.
def Statements
A First Example: Definitions and Calls
Returning values
How To Add Docstrings To A Python
Function
Function Arguments in Python
A Second Example: Intersecting
Sequences
lambda Basics – Anonymous Functions
Why Use lambda?
Multiway branch switches: The finale
Scopes: lambdas Can Be Nested Too
Python Scope Basics
• The enclosing module is a global scope.
• The global scope spans a single file only.
• Assigned names are local unless declared
global or nonlocal.
• All other names are enclosing function locals,
globals, or built-ins.
• Each call to a function creates a new local
scope.
The Built-in Scope
Redefining built-in names: For better
or worse
The global Statement
• Global names are variables assigned at the top
level of the enclosing module file.
• Global names must be declared only if they
are assigned within a function.
• Global names may be referenced within a
function without being declared.
Examples
Program Design: Minimize Global
Variables
Program Design: Minimize Cross-File
Changes
Other Ways to Access Globals

You might also like