Download Functions, modules

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Python Crash Course
Functions, Modules
3rd year Bachelors
V1.0
dd 03-09-2013
Hour 5
Introduction to language - functions
Here are simple rules to define a function in Python:
• Function blocks begin with the keyword def followed by the function name and parentheses ( ).
• Any input parameters or arguments should be placed within these parentheses. You can also
define parameters inside these parentheses.
• The code block within every function starts with a colon : and is indented.
• The statement return [expression] exits a function, optionally passing back an expression to the
caller. A return statement with no arguments is the same as return None.
>>>
...
...
...
...
>>>
8.0
>>>
4.0
>>>
4.0
>>>
5.0
>>>
6.0
>>>
6.0
def my_func(x, y=0.0, z=1.0):
a = x + y
b = a * z
return b
my_func(1.0, 3.0, 2.0)
my_func(1.0, 3.0)
my_func(1.0, y=3.0)
my_func(5.0)
my_func(2.0, z=3.0)
my_func(x=2.0, z=3.0)
Introduction to language - functions
>>> def fact(n):
...
if(n==0): return 1;
...
m = 1;
...
k = 1;
...
while(n >= k):
...
m = m * k;
...
k = k + 1;
...
return m;
Recursion:
>>> def fact(n):
...
if n > 0:
...
return n * fact(n-1)
...
return 1
>>> print fact(100)
>>> print fact(1000)
# Recursive call
# exits function returning 1
Introduction to language - functions
The Anonymous Functions:
You can use the lambda keyword to create small anonymous functions. These functions are called
anonymous because they are not declared by using the def keyword.
• Lambda forms can take any number of arguments but return just one value in the form of an
expression. They cannot contain commands or multiple expressions.
• An anonymous function cannot be a direct call to print because lambda requires an expression.
• Lambda functions have their own local namespace and cannot access variables other than those
in their parameter list and those in the global namespace.
#!/usr/bin/python
# Function definition is here
sum = lambda arg1, arg2: arg1 + arg2;
# Now you can call sum as a function
print "Value of total : ", sum( 10, 20 )
print "Value of total : ", sum( 20, 20 )
Value of total : 30
Value of total : 40
Introduction to language - scope
•
•
Variables defined within the function are local to the function.
For variables referenced (by which we mean “used” i.e. on right hand side
of assignment statement) in the function, interpreter looks first in the local
symbol table, then outside (globally).
>>> def fib(n):
... # write Fibonacci series up to n
...
"""Print a Fibonacci series up to
n.""“
...
a, b = 0, 1
...
while a < n:
...
print a,
...
a, b = b, a+b
...
print x
>>> x = “Hi there”
>>> a = 11
>>> print a
11
>>> fib(2000)
0
1
1
.
.
.
987
1597
Hi there
>>> print a
11
Introduction to language - arguments
• e.g. Arguments with default values:
>>> def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):
...
”””Demonstrate default values”””
...
while True:
...
ok = raw_input(prompt)
...
if ok in ('y', 'ye', 'yes'):
...
return True
...
if ok in ('n', 'no', 'nop', 'nope'):
...
return False
...
retries = retries - 1
...
if retries < 0:
...
raise IOError('refusenik user')
...
print complaint
List comprehensions
• A neat way of creating lists (and arrays) without writing a loop
a = [ x**2 for x in range(10)]
my_fav_num = [3, 17, 22, 46, 71, 8]
even_squared = []
for n in my_fav_num:
if n%2 == 0:
even_squared.append(n**2)
# in one line:
even_better = [n**2 for n in my_fav_num if n%2 == 0]
# both produce [484, 2116, 64
freshfruit = [' banana', ' loganberry ', 'passion fruit
stripped = [weapon.strip() for weapon in freshfruit]
print(stripped)
['banana', 'loganberry', 'passion fruit']
']
Introduction to language - Modules
def print_func( par ):
print "Hello : ", par
return
#!/usr/bin/python
# Import module hello
import hello
# Now you can call defined function that module as follows
hello.print_func(“Earth")
Hello : Earth
from modname import name1[, name1[, … nameN]]
from modname import *
Importing into the current namespace should be done with care due to name clashes
Introduction to languge - Modules
When you import a module, the Python interpreter searches for the module in the
following sequences:
•The current directory.
•If the module isn't found, Python then searches each directory in the shell variable
PYTHONPATH.
•If all else fails, Python checks the default path. On UNIX, this default path is normally
/usr/local/lib/python/.
The module search path is stored in the system module sys as the sys.path variable. The
sys.path variable contains the current directory, PYTHONPATH, and the installationdependent default.
PYTHONPATH is an environment variable, consisting of a list of directories. The syntax of
PYTHONPATH is the same as that of the shell variable PATH.
/software/local/lib64/python2.7/site-packages
Introduction to language - modules
Frequently used modules
•
•
•
•
•
•
•
•
•
•
sys Information about Python itself (path, etc.)
os Operating system functions
os.path Portable pathname tools
shutil Utilities for copying files and directory trees
cmp Utilities for comparing files and directories
glob Finds files matching wildcard pattern
re Regular expression string matching
time Time and date handling
datetime Fast implementation of date and time handling
doctest, unittest Modules that facilitate unit test
Introduction to language - modules
More frequently used modules
• pdb Debugger
• hotshot Code profiling
• pickle, cpickle, marshal, shelve Used to save objects and code to
files
• getopt, optparse Utilities to handle shell-level argument parsing
• math, cmath Math functions (real and complex) faster for scalars
• random Random generators (likewise)
• gzip read and write gzipped files
• struct Functions to pack and unpack binary data structures
• StringIO, cStringIO String-like objects that can be read and written
as files (e.g., in-memory files)
• types Names for all the standard Python type
Introduction to language - modules
Modules are searched for in the following places:
• the current working directory (for interactive sessions)
• the directory of the top-level script file (for script files)
• the directories defined in PYTHONPATH
• Standard library directories
>>> # Get the complete module search path:
>>> import sys
>>> print sys.path
Introduction to language - modules
• Modules can contain any code
• Classes, functions, definitions, immediately executed code
• Can be imported in own namespace, or into the global namespace
>>> import math
>>> math.cos(math.pi)
-1.0
>>> math.cos(pi)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'pi' is not defined
>>> from math import cos, pi
>>> cos(pi)
-1.0
>>> from math import *
Introduction to language - modules
>>> from math import
>>> print sin(1.0)
>>> print cos(1.0) #
>>> from math import
>>> # All attributes
Extremely dangerous
>>> print tan(1.0)
sin
won’t work
*
copied to global namespace
• Use from...import and import...as with care. Both make your code
harder to understand.
• Do not sacrifice code clearness for some keystrokes!
• In some cases, the use is acceptable:
– In interactive work (import math as m)
– If things are absolutely clear (e.g. all functions of an imported module
obey a clear naming convention; cfits_xyz) import.. as: As last resort in
case of name clashes between module names
Introduction to language - modules
•
Inspecting module methods
>>> import numpy
>>> dir(numpy)
['ALLOW_THREADS', 'BUFSIZE', 'CLIP', 'ComplexWarning', 'DataSource', 'ERR_CALL',
'ERR_DEFAULT', 'ERR_DEFAULT2', 'ERR_IGNORE', 'ERR_LOG', 'ERR_PRINT', 'ERR_RAISE',
'ERR_WARN', 'FLOATING_POINT_SUPPORT', 'FPE_DIVIDEBYZERO', 'FPE_INVALID',
'FPE_OVERFLOW', 'FPE_UNDERFLOW', 'False_', 'Inf', 'Infinity', 'MAXDIMS', 'MachAr',
'NAN', 'NINF', 'NZERO', 'NaN', 'PINF', 'PZERO', 'PackageLoader', 'RAISE',
'RankWarning', 'SHIFT_DIVIDEBYZERO', 'SHIFT_INVALID', 'SHIFT_OVERFLOW',
'SHIFT_UNDERFLOW', 'ScalarType', 'Tester', 'True_', 'UFUNC_BUFSIZE_DEFAULT',
'UFUNC_PYVALS_NAME', 'WRAP', '__NUMPY_SETUP__', '__all__', '__builtins__',
'__config__', '__doc__', '__file__', '__git_revision__', '__name__', '__package__',
'__path__', '__version__', '_import_tools', '_mat', 'abs', 'absolute', 'add',
'add_docstring', 'add_newdoc', 'add_newdocs', 'alen', 'all', 'allclose', 'alltrue',
'alterdot', 'amax', 'amin', 'angle', 'any', 'append', 'apply_along_axis',
...
'typeNA', 'typecodes', 'typename', 'ubyte', 'ufunc', 'uint', 'uint0', 'uint16',
'uint32', 'uint64', 'uint8', 'uintc', 'uintp', 'ulonglong', 'unicode', 'unicode0',
'unicode_', 'union1d', 'unique', 'unpackbits', 'unravel_index', 'unsignedinteger',
'unwrap', 'ushort', 'vander', 'var', 'vdot', 'vectorize', 'version', 'void', 'void0',
'vsplit', 'vstack', 'where', 'who', 'zeros', 'zeros_like']
Introduction to language - modules
•
Importing submodules
>>> import numpy
>>> numpy.random # Submodule
>>> numpy.random.randn() # Function in submodule
---------------------------------- (Restart Python)
>>> import numpy.random # Import submodule only
>>> numpy.random.randn()
---------------------------------- (Restart Python)
>>> from numpy import random # Alternative form
>>> random.randn()
---------------------------------- (Restart Python)
>>> from numpy.random import * # Previous warnings
>>> randn() # apply here as well!
Your own package
The main difference between a module and a package is that a
package is a collection of modules AND it has an __init__.py file.
myMath/
__init__.py
adv/
__init__.py
sqrt.py
add.py
subtract.py
multiply.py
divide.py
# add.py
# sqrt.py
def add(x, y):
import math
""""""
return x + y
def squareroot(n):
""""""
return math.sqrt(n)
# outer __init__.py
from add import add
from divide import division
from multiply import multiply
from subtract import subtract
from adv.sqrt import squareroot
import mymath
print
print
print
print
mymath.add(4,5)
mymath.division(4, 2)
mymath.multiply(10, 5)
mymath.squareroot(48))
Introduction to language
End