0
Upcoming SlideShare
×

# Python Intro-Functions

767

Published on

An overview of functional programming in Python, introduction to exceptions.
(C) Sumitava Mukherjee
[smukh@cognobytes.com/ smukh@cbcs.ac.in
URL: http://people.cognobytes.com/smukh]

Published in: Education, Technology
1 Like
Statistics
Notes
• Full Name
Comment goes here.

Are you sure you want to Yes No
• Be the first to comment

Views
Total Views
767
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
17
0
Likes
1
Embeds 0
No embeds

No notes for slide

### Transcript of "Python Intro-Functions"

1. 1. <ul><li>Brief Introduction to Functional programming </li></ul><ul><li>in Python </li></ul><ul><li>Defining Functions </li></ul><ul><li>Arguments in Functions </li></ul><ul><li>What are Modules and how to use the standard modules </li></ul><ul><li>Exception handling </li></ul>Sumitava Mukherjee [email_address] / [email_address] URL: http://people.cognobytes.com/smukh CBCS, Jan 2009
2. 2. Defining Functions >>> def fib(n): # write Fibonacci series up to n &quot;&quot;&quot;Print a Fibonacci series up to n.&quot;&quot;&quot; a, b = 0, 1 while b < n: print b, a, b = b, a+b >>> # Now call the function we just defined: fib(2000)‏ 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 -------------------------------------------------------------------------- Keyword 'def' Documentation strings [ fib.__doc__ ] Symbol table look ups Functions always return only one object/value/None >>> print fib(0)‏ None
3. 3. Playing around ... >>> fib <function fib at 10042ed0> >>> f = fib >>> f(100)‏ 1 1 2 3 5 8 13 21 34 55 89 [symbol table entry can be assigned as others] ---------------------------------------- >>> def sqr(x): return x*x >>> def cube(x): return x*x*x >>> sqr <function sqr at 0x00C556F0> >>> a = [sqr, cube] >>> a[0](2)‏ 4 >>> a[1] (3)‏ 27 --------------------------------------------- Moral: Can manipulate functions as objects!
4. 4. Playing around ..cont.. >>> def sqr(x): return x*x >>> def cube(x): return x*x*x >>> def compose (f,g,x): return f(g(x))‏ >>> compose(sqr,cube,2)‏ 64 ....................................................................................................................... Next > Function arguments
5. 5. Arguments in Functions It is also possible to define functions with a variable number of arguments. There are three forms, which can be combined. (1) Default Argument values (2) Keyword arguments (3) Arbitrary argument list
6. 6. Arguments in Functions ..cont.. Default argument values : def ask_ok(prompt, retries=4, complaint='Yes or no, please!'): 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 This function can be called either like this: ask_ok('Do you really want to quit?') or like this: ask_ok('OK to overwrite the file?', 2)‏ ------------------------------------------------------------------------------------------------------------------- The default values are evaluated at the point of function definition in the defining scope and ONLY ONCE, so that i = 5 def f(arg=i): print arg i = 6 f()‏ will print 5.
7. 7. Arguments in Functions ..cont.. Keyword arguments : Functions can also be called using keyword arguments of the form keyword = value. For instance, the following function: def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'): print &quot;-- This parrot wouldn't&quot;, action, print &quot;if you put&quot;, voltage, &quot;volts through it.&quot; print &quot;-- Lovely plumage, the&quot;, type print &quot;-- It's&quot;, state, &quot;!&quot; could be called in any of the following ways: parrot(1000)‏ parrot(action = 'VOOOOOM', voltage = 1000000)‏ parrot('a thousand', state = 'pushing up the daisies')‏ parrot('a million', 'bereft of life', 'jump')‏ ----------------------------------------------------------------------------------- In general, an argument list must have any positional arguments followed by any keyword arguments, where the keywords must be chosen from the formal parameter names.
8. 8. Arguments in Functions ..cont.. Variable number of arguments : >>> def fool (*args): print len(args)‏ >>> fool(2,3,4)‏ 3 >>> fool(2,3,4,5,)‏ 4 >>> fool()‏ 0
9. 9. Modules A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py appended. Within a module, the module’s name (as a string) is available as the value of the global variable __name__ Say you have a file fibo.py >>> import fibo This does not enter the names of the functions defined in fibo directly in the current symbol table; it only enters the module name fibo there. Using the module name you can access the functions: >>> fibo.fib(1000)‏ 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 you can assign it to a local name: >>> fib = fibo.fib >>> fib(500)‏ 1 1 2 3 5 8 13 21 34 55 89 144 233 377 Multiple Imports: >>> from fibo import fib, fib2 >>> from fibo import *
10. 10. When you run a Python module with python fibo.py <arguments> the code in the module will be executed, just as if you imported it, but with the __name__ set to &quot;__main__&quot;. That means that by adding this code at the end of your module: if __name__ == &quot;__main__&quot;: import sys fib(int(sys.argv[1]))‏ you can make the file usable as a script as well as an importable module, because the code that parses the command line only runs if the module is executed as the “main” file: \$ python fibo.py 50 1 1 2 3 5 8 13 21 34 If the module is imported, the code is not run: >>> import fibo >>> This is often used either to provide a convenient user interface to a module, or for testing purposes (running the module as a script executes a test suite).
11. 11. Standard Modules Python comes with a library of standard modules. Some modules are built into the interpreter; these provide access to operations that are not part of the core of the language but are nevertheless built in, either for efficiency or to provide access to operating system primitives such as system calls. The set of such modules is a configuration option which also depends on the underlying platform For example, the winreg module is only provided on Windows systems. Example : sys, __builtin__ >>> import __builtin__ >>> dir(__builtin__)‏ ['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FloatingPointError', 'FutureWarning',.....**many more**
12. 12. Standard Exception handling Exceptions: >>> 10 * (1/0)‏ Traceback (most recent call last): File &quot;<stdin>&quot;, line 1, in ? ZeroDivisionError : integer division or modulo by zero >>> 4 + spam*3 Traceback (most recent call last): File &quot;<stdin>&quot;, line 1, in ? NameError : name 'spam' is not defined >>> '2' + 2 Traceback (most recent call last): File &quot;<stdin>&quot;, line 1, in ? TypeError : cannot concatenate 'str' and 'int' objects >>> a=[1,2,3] >>> print a[100] Traceback (most recent call last): File &quot;<pyshell#111>&quot;, line 1, in <module> print a[100] IndexError : list index out of range
13. 13. >>> while True: ... try: ... x = int(raw_input(&quot;Please enter a number: &quot;))‏ ... break ... except ValueError: ... print &quot;Oops! That was no valid number. Try again...&quot; ... The try statement works as follows: First, the try clause (the statement(s) between the try and except keywords) is executed. If no exception occurs, the except clause is skipped and execution of the try statement is finished. If an exception occurs during execution of the try clause, the rest of the clause is skipped. Then if its type matches the exception named after the except keyword, the except clause is executed, and then execution continues after the try statement. If an exception occurs which does not match the exception named in the except clause, it is passed on to outer try statements; if no handler is found, it is an unhandled exception and execution stops with a message.
14. 14. A try statement may have more than one except clause, to specify handlers for different exceptions. try: simval= (wordnet.N[something[i].strip()][0].path_similarity(wordnet.N[something[j].strip()][0]))‏ print 'For', something[i].strip(),' and ', something[j].strip(), ' similarity value is : ', simval score+=simval except KeyError: pass except ValueError: pass finally: pass
1. #### A particular slide catching your eye?

Clipping is a handy way to collect important slides you want to go back to later.