Python Intro-Functions

50 %
50 %
Information about Python Intro-Functions

Published on March 12, 2009

Author: sumitavamukh



An overview of functional programming in Python, introduction to exceptions.
(C) Sumitava Mukherjee

Brief Introduction to Functional programming in Python Defining Functions Arguments in Functions What are Modules and how to use the standard modules Exception handling Sumitava Mukherjee [email_address] / [email_address] URL: CBCS, Jan 2009

Brief Introduction to Functional programming

in Python

Defining Functions

Arguments in Functions

What are Modules and how to use the standard modules

Exception handling

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

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!

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

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

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.

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.

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

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 >>> 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 *

When you run a Python module with python <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 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).

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**

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

>>> 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.

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

Add a comment

Related presentations

Related pages

3. An Informal Introduction to Python — Python 2.7.13 ...

3. An Informal Introduction to Python¶ In the following examples, input and output are distinguished by the presence or absence of prompts (>>> and ...
Read more

Python in TouchDesigner | Intro to Functions | TouchDesigner

Python in TouchDesigner | Intro to Functions | TouchDesigner. Core Concepts. ... As you already know, Python gives you many built-in functions like print
Read more

Python in TouchDesigner | Intro To Functions ...

Python in TouchDesigner | Intro To Functions | TouchDesigner Matthew Ragan. Subscribe Subscribed Unsubscribe 976 976. Loading ...
Read more

Python Intro-Functions - Education - documents

1. Brief Introduction to Functional programming . in Python . Defining Functions . Arguments in Functions . What are Modules and how to use the standard ...
Read more

Learn Python Programming Tutorial 19 | Intro to Functions ...

Want to watch this again later? Sign in to add this video to a playlist. In this python programming tutorial we learn about functions. For more ...
Read more

Python lesson 1: Basic Intro Article | Hellbound Hackers

Basic Intro To Python. First of all, this is not going to be the definitive beginners guide. There are already plenty of good ones, so I'm not going to ...
Read more

Need help with Intro to Functions! : learnpython -

Hello, I am in need of help! I am just learning python and in my class im just learning about functions. Here is the code I am begninning. It is...
Read more

Game Keys ( — Blender v2.59.0 - API documentation

Python API • Wiki; Navigation ... Intro; Functions; Keys (Constants) Mouse Keys; Keyboard Keys. Alphabet keys; Number keys; Modifiers Keys; Arrow Keys ...
Read more