overview intro to functions what are functions? why use functions? defining functions calling...

37
Overview Intro to functions What are functions? Why use functions? Defining functions Calling functions Documenting functions Top-down design Variable scope and functions Parameters and arguments Global variables and constants Intro to Modules What are modules? Why use modules? Importing and reloading Scope re-visited (Namespaces) Useful modules sys module and sys.argv Module name and __main__

Upload: david-watson

Post on 04-Jan-2016

237 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: Overview Intro to functions What are functions? Why use functions? Defining functions Calling functions Documenting functions Top-down design Variable

Overview

Intro to functionsWhat are functions?Why use functions?Defining functionsCalling functionsDocumenting functionsTop-down designVariable scope and functionsParameters and argumentsGlobal variables and constants

Intro to ModulesWhat are modules?Why use modules?Importing and reloadingScope re-visited (Namespaces)Useful modulessys module and sys.argvModule name and __main__

Page 2: Overview Intro to functions What are functions? Why use functions? Defining functions Calling functions Documenting functions Top-down design Variable

What is a Function?

A function is a named sequence of statements that exists within a program to perform a specific taskSome are built-in to Python – dir(), help(), str(), int(), float(), input(), raw_input(), etc.Some are provided in other modules (e.g. math)Others you will code yourself …

Page 3: Overview Intro to functions What are functions? Why use functions? Defining functions Calling functions Documenting functions Top-down design Variable

Why use functions?

DRY – Don’t Repeat Yourself

Breaks long sequence of statements into function calls with names that convey what the group of statements do

Code is easier (faster) to: ReadReuseTest

Facilitates teamwork

vs.

Page 4: Overview Intro to functions What are functions? Why use functions? Defining functions Calling functions Documenting functions Top-down design Variable

Defining functions

Function definitions are composed of a function header (first line – including “:” !) and indented function block (body) with one or more statements

Function names cannot Be a Python keywordContain spacesBegin with a number or special character (except _ )Be called before they are defined

Function names arecamelCase in Python (PascalCase in C#)Verb clauses describing task

(e.g. getPopulationData)CaSE SenSItIve

Syntax:def functionName([params]): # Function Header pass # Function [return someObject] # body

Page 5: Overview Intro to functions What are functions? Why use functions? Defining functions Calling functions Documenting functions Top-down design Variable

Calling functions

Functions are called by name followed by parentheses (That may or may not contain arguments depending on whether or not the function definition contains parameters – more later)

Page 6: Overview Intro to functions What are functions? Why use functions? Defining functions Calling functions Documenting functions Top-down design Variable

Parameters and arguments

A parameter is a variable that receives an argument passed to a function.A parameter is local variable to the function definition An argument is data passed to a function when it is called.

messageText = parameter

“I love spam” = argument

Page 7: Overview Intro to functions What are functions? Why use functions? Defining functions Calling functions Documenting functions Top-down design Variable

Multiple parameters and arguments

Page 8: Overview Intro to functions What are functions? Why use functions? Defining functions Calling functions Documenting functions Top-down design Variable

Variable scope and functions

Variable scope = the parts of a program that can access (“see”) the variable.Local = accessible inside a function = can reuse variable names in different functions

Page 9: Overview Intro to functions What are functions? Why use functions? Defining functions Calling functions Documenting functions Top-down design Variable

Global variables and constants

Global = accessible to all functions in a program fileLimit the use of global variables !!!! They make debugging difficult and life miserableUse global constants where possible (UPPERCASE names).

Page 10: Overview Intro to functions What are functions? Why use functions? Defining functions Calling functions Documenting functions Top-down design Variable

Function with return

Page 11: Overview Intro to functions What are functions? Why use functions? Defining functions Calling functions Documenting functions Top-down design Variable

Return as short-circuit for function

If return statement is executed in a function, the interpreterreturns to statement that made the function call. No otherlines in the function are executed.

Page 12: Overview Intro to functions What are functions? Why use functions? Defining functions Calling functions Documenting functions Top-down design Variable

Use clear function and variable names

Most function names should be verb phrases not noun phrases.

Variable names should convey what their value is.

Boolean functions (return bool)should ask a yes/no question.

Page 13: Overview Intro to functions What are functions? Why use functions? Defining functions Calling functions Documenting functions Top-down design Variable

Documenting a FunctionSingle-line string (single or double quoted) or multi-line string (triple quoted) immediately following the function definition statement.

Page 14: Overview Intro to functions What are functions? Why use functions? Defining functions Calling functions Documenting functions Top-down design Variable

Top-down design

Break overall task into sub-tasksBreak sub-tasks into sub-tasks if possibleWhen complete, write “leaf” functions and work back to trunk (testing as you go)

Call list

Page 15: Overview Intro to functions What are functions? Why use functions? Defining functions Calling functions Documenting functions Top-down design Variable

Incremental development

Start with a simple test and function skeleton.

Run test repeatedly as you debug function under test.

Page 16: Overview Intro to functions What are functions? Why use functions? Defining functions Calling functions Documenting functions Top-down design Variable

Overview

Intro to functionsWhat are functions?Why use functions?Defining functionsCalling functionsDocumenting functionsTop-down designVariable scope and functionsParameters and argumentsGlobal variables and constants

Intro to ModulesWhat are modules?Why use modules?Importing and reloadingScope re-visited (Namespaces)Useful modulessys module and sys.argvModule name and __main__

Page 17: Overview Intro to functions What are functions? Why use functions? Defining functions Calling functions Documenting functions Top-down design Variable

What are Modules?

Modules are most typically .py or pyc files but can be DLL, etcMany modules and packages (groups of modules) shipped with Python (e.g. sys, os, math, turtle, etc.) Local modules (in same folder as running .py) override other modules in folders.

Example: arcgisscripting.py in local folder will override C:\Program Files\ArcGIS\bin\arcgisscripting.dll this is NOT a good thing.

Page 18: Overview Intro to functions What are functions? Why use functions? Defining functions Calling functions Documenting functions Top-down design Variable

Why use Modules?

Code reuseSaves code permanently to diskCan be referenced (imported) by multiple client modulesDefine data and methods that can be used in programs

Namespace partitioningSeals up names to avoid name clashes … e.g. two modules can have functions with the same name

Page 19: Overview Intro to functions What are functions? Why use functions? Defining functions Calling functions Documenting functions Top-down design Variable

- If you run a module as a program, the built-in __name__ attribute contains __main__. - If you import, __name__ contains the name of the module (no .py extension).- Convention is to put this block at the end of the module.

How: Module contents and structure

Most modules have one or more of the attributes shown below

Page 20: Overview Intro to functions What are functions? Why use functions? Defining functions Calling functions Documenting functions Top-down design Variable

import <module> / from <module> import …

Import is only run once / module / Python session

If you edit the module file with external editor and save, and you are in the same Python session, then the updated file WILL NOT BE IMPORTED!Using from <module> import <name(s)> means you do not have to qualify the names with the module name

del () removes names

from program

B.py run twice …

Page 21: Overview Intro to functions What are functions? Why use functions? Defining functions Calling functions Documenting functions Top-down design Variable

reload(module)

The reload() function forces a module to reload – run its code.In an active session, Python is not aware of updates in imported modulesReally useful during program developmentShould not be used with stable modules

Page 22: Overview Intro to functions What are functions? Why use functions? Defining functions Calling functions Documenting functions Top-down design Variable

import steps

Find the module’s fileSearch folders in following order:

Folder containing the programPYTHONPATH directories (if it is set)Standard library directories

Compile it to byte code (maybe)If .py newer than .pyc and if file is imported

Run the module’s code to build the objects it defines

}

Page 23: Overview Intro to functions What are functions? Why use functions? Defining functions Calling functions Documenting functions Top-down design Variable

Structuring a Python program

a.py

b.py c.py

Std Library modules

Top-level module that controlsprogram flow. Imports b.

b and c import each other …not usually a good thing

and may import 0 or moreof the standard library modulesand 0 or more “other” modules

Other modules

Page 24: Overview Intro to functions What are functions? Why use functions? Defining functions Calling functions Documenting functions Top-down design Variable

Namespaces

Page 25: Overview Intro to functions What are functions? Why use functions? Defining functions Calling functions Documenting functions Top-down design Variable

Scope rules

Python searches for names in LEGB order and stops at the first name it finds (i.e. Local x takes precedence over EGB

Local: in a function and not declared global (e.g. global x)Enclosing functions: nested functions

Not covered in this course

Global (module): names at top-level of moduleBuilt-in: names in Python built-in names module (e.g. open, range, etc.)

Page 26: Overview Intro to functions What are functions? Why use functions? Defining functions Calling functions Documenting functions Top-down design Variable

Built-in & Standard Python library modules

Built-in functions can be called without importing any module

Standard Python Library modules must be imported to gain access to functions, etc.

Page 27: Overview Intro to functions What are functions? Why use functions? Defining functions Calling functions Documenting functions Top-down design Variable

Some useful Python Modules

globmathosos.pathshutilsyszipfile

Page 28: Overview Intro to functions What are functions? Why use functions? Defining functions Calling functions Documenting functions Top-down design Variable

sys module & command line args (sys.argv)

Command line args are stored in sys.argv

Page 29: Overview Intro to functions What are functions? Why use functions? Defining functions Calling functions Documenting functions Top-down design Variable

sys.exit([arg])

The exit function in stops execution of a Python program

Page 30: Overview Intro to functions What are functions? Why use functions? Defining functions Calling functions Documenting functions Top-down design Variable

os and os.path module

Access to operating system properties / operations

Get/Set environment variables, get current directory, creating/deleting directories, path/file info, split/join paths Three ways to specify paths

in Python:

Page 31: Overview Intro to functions What are functions? Why use functions? Defining functions Calling functions Documenting functions Top-down design Variable

os.path module (splitting/joining paths)

Page 32: Overview Intro to functions What are functions? Why use functions? Defining functions Calling functions Documenting functions Top-down design Variable

glob - Filename globbing utility

The glob module finds all the pathnames matching a specified pattern

Page 33: Overview Intro to functions What are functions? Why use functions? Defining functions Calling functions Documenting functions Top-down design Variable

shutil – file/dir tree copy/move/delete(rm)

The shutil module offers a number of high-level operations on files and collections of files. In particular, functions are provided which support file copying and removal.

Implementation of shutil.copytree

Page 34: Overview Intro to functions What are functions? Why use functions? Defining functions Calling functions Documenting functions Top-down design Variable

Other modules

zipfile module – working with .zip files (read, write, get info, etc.)

The urllib2 module defines functions and classes which help in opening URLs (mostly HTTP)

Page 35: Overview Intro to functions What are functions? Why use functions? Defining functions Calling functions Documenting functions Top-down design Variable

main()

Most programs contain a function called main that has the a program’s mainline logicThat is, standalone statements and calls to other functions in a logical order.

Page 36: Overview Intro to functions What are functions? Why use functions? Defining functions Calling functions Documenting functions Top-down design Variable

__main__ and main()

In many Python scripts you will find the following at the bottom of modules

In plain English … If the module is running as a program (i.e. not imported), then __name__ will be __main__ so call the main() function defined in the module.If the module was imported, __name__ will be the name of the module and main() will not be called.

Page 37: Overview Intro to functions What are functions? Why use functions? Defining functions Calling functions Documenting functions Top-down design Variable

Lib, Modules, function mind map