Title: Geography 465 Modules and Functions Writing Custom Functions
1Geography 465 Modules and FunctionsWriting
Custom Functions
2Python Modules
- Each Python script is a module
- Modules can access other modules
- Modules can use variables and/or constants
- Modules can use functions
3Writing 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
4Syntax Example
- MyCustomFunction.py
- Def ltnamegt (arg1, arg2, argN)
- your custom function code
- return ltvaluegt
5Code example result of two numbers
- MyFunctions.py
- def calculate(num1, num2, mathOp)
- result eval(str(num1) mathOp str(num2))
- return result
Interactive Window gtgtgt import MyFunctions gtgtgt
MyFunctions.calculate (3, 4, ) gtgtgt 7
6Using 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
Passing values to module function
NewYork.py lat -73.905 Global long
40.708 Global def calcgrowth(pop,
rate) growth pop rate return growth
7Importing 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
8Finding 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
9Adding 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\\MyModu
les) Print sys.path
10Reloading a modulesingle 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 Window NewYork.py
- gtgtgt reload(NewYork) Access modified lat
-73.905 - NewYork.py long 40.708
11Running the module
- All statements execute from top to bottom
- Statements do not exist until Python reaches and
runs code - 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