Date post: | 29-Dec-2015 |
Category: |
Documents |
Upload: | maximillian-allen |
View: | 232 times |
Download: | 4 times |
Python Crash CoursePython Crash CourseFunctions, ModulesFunctions, Modules
Bachelors
V1.0
dd 20-01-2014
Hour 1
Introduction to language - functionsIntroduction to language - functions
What are functionsA function is a piece of code in a program. The function performs a specific task. The advantages of using functions are:•Reducing duplication of code•Decomposing complex problems into simpler pieces•Improving clarity of the code•Reuse of code•Information hiding
Functions in Python are first-class citizens. It means that functions have equal status with other objects in Python. Functions can be assigned to variables, stored in collections or passed as arguments. This brings additional flexibility to the language.
Function typesThere are two basic types of functions. Built-in functions and user defined ones. The built-in functions are part of the Python language. Examples are: dir(), len() or abs().
Introduction to language - functionsIntroduction to language - functions
>>> def my_func(x, y, z):
... a = x + y
... b = a * z
... return b
...
>>>
Defining FunctionsHere 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.
>>> my_func(1.0, 3.0, 2.0)
8.0
>>> my_func(1.0, 3.0, 1.0)
4.0
>>> my_func(5.0, 0.0, 1.0)
5.0
>>> my_func(2.0, 0,0 3.0)
6.0
Introduction to language - functionsIntroduction to language - functions
#!/usr/bin/python
def f1():
print "f1()"
f1()
#f2()
def f2():
print "f2()"
Defining FunctionsFunction must be denifed preceding their usage:
#!/usr/bin/python
def f():
print "f() function"
def g():
def f():
print "f() inner function"
f()
f()
g()uncommenting f2()will cause a NameError
where to define functions
inner function definition
Introduction to language - functionsIntroduction to language - functions
• Functions are objects
>>> def f():
... """This function prints a message """
... print "Today it is a cloudy day"
...
>>> f.__doc__
'This function prints a message '
>>> f()
Today it is a cloudy day
>>> id(f)
140491806602016
>>>
>>> def f():
... pass
...
>>> def g():
... pass
...
>>> def h(f):
... print id(f)
...
>>> a=(f, g, h)
>>> for i in a:
... print i
...
<function f at 0x7fc6cc39f320>
<function g at 0x7fc6cc39f398>
<function h at 0x7fc6caab1c80>
>>> h(f)
140491806602016
>>> h(g)
140491806602136
>>>
Introduction to language - functionsIntroduction to language - functions
Functions types•always available for usage•those contained in external modules•programmer defined
>>> from math import sqrt
>>> def cube(x):
... return x * x * x
...
>>> print abs(-1)
1
>>> print cube(9)
729
>>> print sqrt(81)
9.0
Introduction to language - functionsIntroduction to language - functions
The return keyword•is used to return value
•no return returns None
>>> def cube(x):
... return x * x * x
...
>>> def showMessage(msg):
... print msg
...
>>> x = cube(3)
>>> print x
27
>>> showMessage("Some text")
Some text
>>> print showMessage("O, no!")
O, no!
None
>>> showMessage(cube(3))
27
>>>
>>> n = [1, 2, 3, 4, 5]
>>> def stats(x):
... mx = max(x)
... mn = min(x)
... ln = len(x)
... sm = sum(x)
...
... return mx, mn, ln, sm
...
>>> mx, mn, ln, sm = stats(n)
>>> print stats(n)
(5, 1, 5, 15)
>>>
>>> print mx, mn, ln, sm
5 1 5 15
Introduction to language - functionsIntroduction 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) # Recursive call
... return 1 # exits function returning 1
>>> print fact(100)
>>> print fact(1000)
Introduction to language - functionsIntroduction to language - functions
>>> def C2F(c):
... return c * 9/5 + 32
...
>>>
>>> print C2F(100)
212
>>> print C2F(0)
32
>>> print C2F(30)
86
>>>
Function arguments
single arguments
>>> def power(x, y=2):
... r = 1
... for i in range(y):
... r = r * x
... return r
...
>>> print power(3)
9
>>> print power(3, 3)
27
>>> print power(5, 5)
3125
>>>
multiple arguments
Introduction to language - functionsIntroduction to language - functions
>>> def display(name, age, sex):
... print "Name: ", name
... print "Age: ", age
... print "Sex: ", sex
...
>>> display(age=43, name="Lary", sex="M")
Name: Lary
Age: 43
Sex: M
>>> display(name="Joan", age=24, sex="F")
Name: Joan
Age: 24
Sex: F
>>> display("Joan", sex="F", age=24)
Name: Joan
Age: 24
Sex: F
>>> display(age=24, name="Joan", "F")
File "<stdin>", line 1
SyntaxError: non-keyword arg after keyword arg
>>>
Function arguments
named arguments
• order may be changed• default value
Introduction to language - functionsIntroduction to language - functions
>>> def sum(*args):
... '''Function returns the sum
... of all values'''
... s = 0
... for i in args:
... s += i
... return s
...
>>>
>>> print sum.__doc__
Function returns the sum
of all values
>>> print sum(1, 2, 3)
6
>>> print sum(1, 2, 3, 4, 5)
15
>>>
Function arguments
arbitrary number of arguments
Introduction to language - functionsIntroduction to language - functions
>>> n = [1, 2, 3, 4, 5]
>>>
>>> print "Original list:", n
Original list: [1, 2, 3, 4, 5]
>>>
>>> def f(x):
... x.pop()
... x.pop()
... x.insert(0, 0)
... print "Inside f():", x
...
...
>>> f(n)
Inside f(): [0, 1, 2, 3]
>>>
>>> print "After function call:", n
After function call: [0, 1, 2, 3]
>>>
Function arguments
passing by reference
Passing objects by reference has two important conclusions. The process is faster than if copies of objects were passed. Mutable objects that are modified in functions are permanently changed.
Introduction to language - functionsIntroduction to language - functions
>>> name = "Jack"
>>> def f():
... name = "Robert"
... print "Within function", name
...
>>> print "Outside function", name
Outside function Jack
>>> f()
Within function Robert
>>> def f():
... print "Within function", name
...
>>> print "Outside function", name
Outside function Jack
>>> f()
Within function Jack
>>>
Function variables
Global and Local
A variable defined in a function body has a local scope
We can get the contents of a global variable inside the body of a function. But if we want to change a global variable in a function, we must use the global keyword.
>>> name = "Jack"
>>> def f():
... global name
... name = "Robert"
... print "Within function", name
...
>>> print "Outside function", name
Outside function Jack
>>> f()
Within function Robert
>>> print "Outside function", name
Outside function Robert
>>>
Introduction to language - functionsIntroduction 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 languge - ModulesIntroduction to languge - Modules
What are modules for?Python modules are used to organize Python code. For example, database related code is placed inside a database module, security code in a security module etc. Smaller Python scripts can have one module. But larger programs are split into several modules. Modules are grouped together to form packages.
Modules namesA module name is the file name with the .py extension. When we have a file called empty.py, empty is the module name. The __name__ is a variable that holds the name of the module being referenced. The current module, the module being executed (called also the main module) has a special name: '__main__'. With this name it can be referenced from the Python code.
Introduction to language - ModulesIntroduction to language - Modules
$ cat hello.py
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
>>> print __name__
__main__
>>> print hello.__name__
hello
>>>
Importing into the current namespace should be done with care due to name clashes
Introduction to languge - ModulesIntroduction 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/lib64/python2.7/.
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 installation-dependent 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/usr/lib64/python2.7/site-packages
Introduction to language - modulesIntroduction 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
['', '/software/local/lib64/python2.7/site-packages/Astropysics-0.1.dev_r1161-
py2.7.egg', '/software/local/lib64/python2.7/site-packages/CosmoloPy-0.1.104-py2.7-
linux-x86_64.egg', '/software/local/lib64/python2.7/site-packages/pyregion-1.1_git-
py2.7-linux-x86_64.egg', '/software/local/lib64/python2.7/site-packages/scikit_image-
0.9dev-py2.7-linux-x86_64.egg',
'/software/local/lib64/python2.7/site-packages/memory_profiler-0.26-py2.7.egg',
'/software/local/lib64/python2.7/site-packages/agpy-0.1.1-py2.7.egg',
'/software/local/lib64/python2.7/site-packages/APLpy-0.9.12-py2.7.egg',
'/software/local/lib64/python2.7/site-packages/pandas-0.14.1-py2.7-linux-x86_64.egg',
'/software/local/lib64/python2.7/site-packages/astroquery-0.2.3-py2.7.egg',
'/software/local/lib64/python2.7/site-packages/html5lib-1.0b3-py2.7.egg',
'/software/local/lib64/python2.7/site-packages/beautifulsoup4-4.3.2-py2.7.egg',
'/software/local/lib64/python2.7/site-packages/requests-2.4.3-py2.7.egg',
'/software/local/lib64/python2.7/site-packages/PIL-1.1.7-py2.7-linux-x86_64.egg',
'/software/local/lib64/python2.7/site-packages/astLib-0.8.0-py2.7-linux-x86_64.egg',
'/software/local/lib64/python2.7/site-packages/setuptools-6.0.2-py2.7.egg',
'/software/local/lib64/python2.7/site-packages/pip-1.5.6-py2.7.egg',
'/software/local/lib64/python2.7/site-packages/Jinja-1.2-py2.7-linux-x86_64.egg',
'/software/local/lib64/python2.7/site-packages/Jinja2-2.7.3-py2.7.egg',
'/software/local/lib64/python2.7/site-packages/pyraf-2.1.6-py2.7-linux-x86_64.egg',
'/software/local/lib64/python2.7/site-packages/pyfits-3.1.6-py2.7-linux-x86_64.egg',
'/software/local/lib64/python2.7/site-packages/numexpr-2.4-py2.7-linux-x86_64.egg',
'/software/local/lib64/python2.7/site-packages/tables-3.1.1-py2.7-linux-x86_64.egg',
'/usr/lib/python2.7/site-packages/lmfit-0.7.4-py2.7.egg', '/usr/lib64/python2.7/site-
packages/mpich', '/software/fc20/lib64/python2.7/site-packages',
'/software/local/lib64/python2.7/site-packages',
'/home/deul/.local/lib/python2.7/site-packages', '/usr/lib64/python27.zip',
'/usr/lib64/python2.7', '/usr/lib64/python2.7/plat-linux2', '/usr/lib64/python2.7/lib-
tk', '/usr/lib64/python2.7/lib-old', '/usr/lib64/python2.7/lib-dynload',
'/usr/lib64/python2.7/site-packages', '/usr/lib64/python2.7/site-packages/Numeric',
'/usr/lib64/python2.7/site-packages/gst-0.10',
'/usr/lib64/python2.7/site-packages/gtk-2.0', '/usr/lib64/python2.7/site-packages/wx-
2.8-gtk2-unicode', '/usr/lib/python2.7/site-packages']
Introduction to language - modulesIntroduction 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 - modulesIntroduction 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 - modulesIntroduction 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 - modulesIntroduction to language - modules
Module import
This construct will import all Python definitions into the namespace of another module. he use of this import construct may result in namespace pollution. We may have several objects of the same name and their definitions can be overridden.
No _ names are imported
>>> from math import *
#!/usr/bin/python
"""
names is a test module
"""
_version = 1.0
names = ["Paul", "Frank", "Jessica"]
def show_names():
for i in names:
print i
def _show_version():
print _version
>>> from names import *
>>> print locals()
{'__builtins__': <module '__builtin__'
(built-in)>, '__file__': './private.py',
'show_names': <function show_names at
0xb7dd233c>,
'names': ['Paul', 'Frank', 'Jessica'],
'__name__': '__main__', '__doc__':
None}
>>> show_names()
Paul
Frank
Jessica
Introduction to language - modulesIntroduction to language - modules
• 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
>>> from math import sin
>>> print sin(1.0)
>>> print cos(1.0) # won’t work
>>> from math import *
>>> # All attributes copied to global namespace
Extremely dangerous
>>> print tan(1.0)
Introduction to language - modulesIntroduction to language - modules
>>> 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']
• Inspecting module methods
Introduction to language - modulesIntroduction to language - modules
Executing modulesModules can be imported into other modules or they can be also executed. Module authors often create a testing suite to test the module. Only if the module is executed as a script, the __name__ attribute equals to __main__.
#!/usr/bin/python
"""
A module containing the fibonacci
function.
"""
def fib(n):
a, b = 0, 1
while b < n:
print b,
(a, b) = (b, a + b)
# testing
if __name__ == '__main__':
fib(500)
$ ./fibonacci.py
1 1 2 3 5 8 13 21 34 55 89 144 233 377
Introduction to language - modulesIntroduction to language - modules
>>> 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!
• Importing submodules
Your own packageYour own package
myMath/
__init__.py
adv/
__init__.py
sqrt.py
add.py
subtract.py
multiply.py
divide.py
# 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 mymath.add(4,5)
print mymath.division(4, 2)
print mymath.multiply(10, 5)
print mymath.squareroot(48))
# add.py
def add(x, y):
""""""
return x + y
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.
# sqrt.py
import math
def squareroot(n):
""""""
return math.sqrt(n)