Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Overview Intro to functions What are functions? Why use functions? Defining functions Calling functions Documenting functions Top-down design Variable."— Presentation transcript:

1 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__

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

3 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: Read Reuse Test Facilitates teamwork vs.

4 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 keyword Contain spaces Begin with a number or special character (except _ ) Be called before they are defined Function names are camelCase 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

5 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)

6 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

7 Multiple parameters and arguments

8 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

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

10 Function with return

11 Return as short-circuit for function If return statement is executed in a function, the interpreter returns to statement that made the function call. No other lines in the function are executed.

12 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.

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

14 Top-down design Break overall task into sub-tasks Break sub-tasks into sub-tasks if possible When complete, write “leaf” functions and work back to trunk (testing as you go) Call list

15 Incremental development Start with a simple test and function skeleton. Run test repeatedly as you debug function under test.

16 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__

17 What are Modules? Modules are most typically.py or pyc files but can be DLL, etc Many 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.

18 Why use Modules? Code reuse Saves code permanently to disk Can be referenced (imported) by multiple client modules Define data and methods that can be used in programs Namespace partitioning Seals up names to avoid name clashes … e.g. two modules can have functions with the same name

19 - 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

20 import / from 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 import means you do not have to qualify the names with the module name del () removes names from program B.py run twice …

21 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 modules Really useful during program development Should not be used with stable modules

22 import steps Find the module’s file Search folders in following order: Folder containing the program PYTHONPATH 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 }

23 Structuring a Python program a.py b.pyc.py Std Library modules Top-level module that controls program flow. Imports b. b and c import each other … not usually a good thing and may import 0 or more of the standard library modules and 0 or more “other” modules Other modules

24 Namespaces

25 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 module Built-in: names in Python built-in names module (e.g. open, range, etc.)

26 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.

27 Some useful Python Modules glob math os os.path shutil sys zipfile

28 sys module & command line args (sys.argv) Command line args are stored in sys.argv

29 sys.exit([arg]) The exit function in stops execution of a Python program

30 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:

31 os.path module (splitting/joining paths)

32 glob - Filename globbing utility The glob module finds all the pathnames matching a specified pattern

33 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

34 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)

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

36 __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.

37 Lib, Modules, function mind map


Download ppt "Overview Intro to functions What are functions? Why use functions? Defining functions Calling functions Documenting functions Top-down design Variable."

Similar presentations


Ads by Google