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]
Model Call Girl in Tilak Nagar Delhi reach out to us at π9953056974π
Β
Python Intro-Functions
1.
2. Defining Functions >>> def fib(n): # write Fibonacci series up to n """Print a Fibonacci series up to n.""" 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. 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. 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. 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. 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. 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 "-- This parrot wouldn't", action, print "if you put", voltage, "volts through it." print "-- Lovely plumage, the", type print "-- It's", state, "!" 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. 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. 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. 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 "__main__". That means that by adding this code at the end of your module: if __name__ == "__main__": 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. 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. Standard Exception handling Exceptions: >>> 10 * (1/0)β Traceback (most recent call last): File "<stdin>", line 1, in ? ZeroDivisionError : integer division or modulo by zero >>> 4 + spam*3 Traceback (most recent call last): File "<stdin>", line 1, in ? NameError : name 'spam' is not defined >>> '2' + 2 Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError : cannot concatenate 'str' and 'int' objects >>> a=[1,2,3] >>> print a[100] Traceback (most recent call last): File "<pyshell#111>", line 1, in <module> print a[100] IndexError : list index out of range
13. >>> while True: ... try: ... x = int(raw_input("Please enter a number: "))β ... break ... except ValueError: ... print "Oops! That was no valid number. Try again..." ... 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. 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