Presentation is loading. Please wait.

Presentation is loading. Please wait.

Geography 465 Modules and Functions Writing Custom Functions.

Similar presentations


Presentation on theme: "Geography 465 Modules and Functions Writing Custom Functions."— Presentation transcript:

1 Geography 465 Modules and Functions Writing Custom Functions

2 Python Modules Each Python script is a module Modules can access other modules Modules can use variables and/or constants Modules can use functions

3 Writing a Function What makes a good function –Single, clear objective –Reusable by intent Function syntax –Def defines the function –Return() sends result back to calling module –See example

4 Syntax Example MyCustomFunction.py Def (arg1, arg2, …argN): # your custom function code return

5 Code example result of two numbers MyFunctions.py def calculate(num1, num2, mathOp): result = eval(str(num1) + mathOp + str(num2)) return result Interactive Window >>> import MyFunctions >>> MyFunctions.calculate (3, 4, “+”) >>> 7

6 Using variables in functions Assignment statement –Variables at module level are available to calling script –Variables within a function are local to the function Script1.py import NewYork nyLat = NewYork.lat nyLong = NewYork.long nyCalc = NewYork.calcgrowth (7000000, 0.03) Print nyCalc NewYork.py lat = -73.905# Global long = 40.708# Global def calcgrowth(pop, rate): growth = pop * rate return growth Passing values to module function

7 Importing a custom module First time in Python –Finds the module –Compiles the module –Runs the module Subsequent times (same Python session) –Re-uses imported (compiled) module

8 Finding the module Where does Python look to find module? The search path hierarchy is: –Home directory of calling module –PYTHONPATH environment variable –Standard Python library directions –Contents of.pth (text) files

9 Adding a custom search path Modify sys.path Append location of your custom modules Last for duration of script Resets to default when PythonWin closes Example.py import sys sys.path.append(“C:\\MyModules”) Print sys.path

10 Reloading a module single Python session Module load only once Script1.py NewYork.py import NewYork Access NewYork.py lat = -73 long = 40 To re-import, call reload() Interactive WindowNewYork.py >>> reload(NewYork)Access modifiedlat = -73.905 NewYork.py long = 40.708

11 Running the module All statements execute from top to bottom –Statements do not exist until Python reaches and runs code (line by line interpret) –Code inside functions do not run until called NewYork.py lat = -73.905 long = 40.708 def calcgrowth (pop, rate): growth = pop * rate return growth Follow indent rules


Download ppt "Geography 465 Modules and Functions Writing Custom Functions."

Similar presentations


Ads by Google