A Brief Introduction  “Python is an interpreted, interactive, object-oriented    programming language...  •    Python is I...
Why Python?•   Very Object Oriented     – Python much less verbose than Java•   NLP Processing: Symbolic     – Python has ...
• Built-in high level data types: strings, lists, dictionaries, etc.• The usual control structures: if, if-else, if-elif-e...
Getting Python:The most up-to-date and current source code, binaries, documentation, news,etc. is available at the officia...
On window machine download the Python from the linkhttp://www.python.org/download/releases/2.7.1/Install the software
Select the directory for Python
Select the features to be Installed
Python Shell
Installation on Linux EnvironmentGenerally Python come installed with the Operating SystemBut if it is not available in th...
Alternate WayUbuntu Linux, the another easiest way to install Python 3 is through the Add/Removeapplication in your Applic...
Now the list of applications narrows to just those matching Python 3. You’re going tocheck two packages. The first is Pyth...
The second package you want is immediately above: IDLE (using Python-3.0). Thisis a graphical Python Shell   click the App...
The package manager will ask youto confirm that you want to addboth IDLE (using Python-3.0) andPython (v3.0).Click the App...
The package manager will show youa progress meter while it downloadsthe necessary packagesOnce the packages are downloaded...
If all went well, the package manager will confirm that both packages weresuccessfully installed. From here, you can doubl...
The Python Shell is where you will spend most of your time exploring Python.Examples throughout this book will assume that...
Python leads a dual role in programming• Its an interpreter for scripts that you can run from the command line or run    l...
Enough to Understand the Code• Assignment uses = and comparison uses ==.• For numbers +-*/% are as expected.   – Special u...
Whitespace• Whitespace is meaningful in Python: especially  indentation and placement of newlines.  – Use a newline to end...
Comments• Start comments with # – the rest of line is  ignored.• Can include a “documentation string” as the first  line o...
Variables and types•   Variables are created when they are assigned•   No declaration required•   The variable name is cas...
Numbers• Integers: 12 0 -12987 0123 0X1A2   –   Type ‘int’   –   Can’t be larger than 2**31   –   Octal literals begin wit...
Numeric expressions•   The usual numeric expression operators: +, -, /, *, **, %, //•   Precedence and parentheses work as...
Boolean expressions•   ‘True’ and ‘ False’ are predefined values; actually integers 1 and 0•   Value 0 is considered False...
String>>> a = Hello world!>>> b = "Hello world!">>> a == bTrue>>> a = "Pers lecture">>> print aPers lecture •   Single quo...
String conversions                                               >>> f = float(1.2e-3)                                    ...
String operations•    Common string operations>>> a = "Part 1">>> b = "and part 2">>> a +   + b     # concatenation, addin...
Changing strings. Not!    >>>s=‘gaurav’    >>> s[0] = B‘    Traceback (most recent call last):     File "<pyshell#68>", li...
String methods•   Strings have a set of built-in methods•   No method ever changes the original string!•   Several methods...
• Lists   – e.g.      aList = [631, “Programming languages”,[331,        “programming languages”]]   –   List items need n...
List>>> r = [1, 2.0, 3, 5]      # list literal; different types of values>>> r[1, 2.0, 3, 5]>>> type(r)<type list>>>> r[1]...
List operations•       Lists are mutable; can be changed in-place•       Lists are dynamic; size may be changed    >>> r =...
List methods, part 1    •    Lists have a set of built-in methods    •    Some methods change the list in-place     >>> r ...
List methods, part 2•    Use the built-in sort method: efficient•    The list is sorted in-place; a new list is not produc...
Converting lists between strings>>> s = biovitrum                            # create a string>>> w = list(s)             ...
Dictionary •   An unordered collection of key/value pairs •   Each key maps to a value •   Also called "mapping", "hash ta...
Dictionary methods, part 1>>> h = {key: 12, nyckel: word}>>> Per in h               # test if key in dictionaryFalse>>> h[...
Dictionary methods, part 2>>> g = h.copy()         # a separate copy of the dictionary>>> del h[key]>>> h{nyckel: word}>>>...
•   Tuples    – E.g.        aTuple = (631, “Programming Languages”,611, “Computer           Architecture”)    – Nesting is...
Tuple •   Same as list, except immutable •   Once created, cant be changed •   Some functions return tuples>>> t = (1, 3, ...
Data Type Wrap Up•   Lists, Tuples, and Dictionaries can store any type (including other    lists, tuples, and dictionarie...
IDLE ("Interactive Development Environment")Now we need to write proper scripts, saved in filesIn IDLE:     File     New W...
if statement; block structure•   The Python feature that one either loves or hates•   Block structure is determined by ind...
for statement•   Repetition of a block of statements•   Iterate through a sequence (list, tuple, string, iterator)#t3.pys=...
Built-in functions range and xrange’    •    Built-in functions range and xrange useful with for    •    range creates a l...
Usually, function definitions have the following basic structure:   def func(args):        return valuesRegardless of the ...
How to define your own function•   Use the def statement•   Function body follows; indented!•   This is a statement like o...
Function features•   The value of an argument is not checked for type     – Often very useful; overloading without effort ...
Function arguments: fixed•   Fixed number of arguments•   Associated by order# t6.pydef fixed_args(a, c, b):              ...
Function arguments: variable•     List of any number of arguments•     Useful when unknown number of arguments needed•    ...
Function arguments: default values•   Arguments may have default values•   When argument not given in a call, default valu...
Function arguments: keywords•   Keyword/value arguments•   The argument values collected into a dictionary    – Called kwa...
Function arguments: explicit type checking•   Use the assert statement•   Checks that its Boolean expression is True, else...
Function arguments: local variables•   Arguments become local variables     –    Immutable values are copied, in effect   ...
Function without return: value None•   A function does not have to use the return statement•   If not, then same as a proc...
Defining a ClassA class is a special data type which defines how to build a certain kind ofobject.    The class also store...
Object oriented approachEverything in Python is really an object.     We’ve seen hints of this already…     “hello”.upper(...
Methods in ClassesDefine a method in a class by including function definitions within the scope of theclass block.     The...
Instantiating Objects• There is no “new” keyword as in Java.• Merely use the class name with () notation and assign the re...
class Worker:   def __init__(self, name, pay):   >>> ========= RESTART==========     self.name = name               >>>   ...
InheritanceSubclassesA class can extend the definition of another class    Allows use (or extension ) of methods and attri...
Redefining MethodsTo redefine a method of the parent class, include a newdefinition using the same name in the subclass.  ...
Definition of a class extending studentclass student:“A class representing a student.”         def __init__(self,n,a):  se...
Importing and ModulesUse classes & functions defined in another file.A Python module is a file with the same name (plus th...
import …import somefileEverything in somefile.py gets imported.To refer to something in the file, append the text “somefil...
from … import …from somefile import classNameOnly the item className in somefile.py gets imported.After importing classNam...
Commonly Used ModulesSome useful modules to import, included with Python:Module: sys               - Lots of handy stuff. ...
There are still a lot to cover in python Tutorial…….But you can get the tutorial from following websites…http://docs.pytho...
Python
Python
Python
Python
Python
Python
Python
Python
Python
Python
Python
Python
Python
Python
Upcoming SlideShare
Loading in …5
×

Python

1,953 views

Published on

Published in: Education, Technology
1 Comment
7 Likes
Statistics
Notes
No Downloads
Views
Total views
1,953
On SlideShare
0
From Embeds
0
Number of Embeds
25
Actions
Shares
0
Downloads
1
Comments
1
Likes
7
Embeds 0
No embeds

No notes for slide
  • Natural language processing ( NLP ) is a field of computer science and linguistics concerned with the interactions between computers and human (natural) languages; it began as a branch of artificial intelligence. [1] In theory, natural language processing is a very attractive method of human–computer interaction
  • Python

    1. 1. A Brief Introduction “Python is an interpreted, interactive, object-oriented programming language... • Python is Interpreted • Python is Interactive • Python is Object-Oriented • Python is Beginners Language Python is an open source scripting language. Developed by Guido van Rossum in the early 1990s Named after Monty Python Available on eniac Available for download from http://www.python.org
    2. 2. Why Python?• Very Object Oriented – Python much less verbose than Java• NLP Processing: Symbolic – Python has built-in datatypes for strings, lists, and more.• NLP Processing: Statistical – Python has strong numeric processing capabilities: matrix operations, etc. – Suitable for probability and machine learning code.• NLTK: Natural Language Tool Kit – Widely used for teaching NLP – First developed for this course – Implemented as a set of Python modules – Provides adequate libraries for many NLP building blocks.
    3. 3. • Built-in high level data types: strings, lists, dictionaries, etc.• The usual control structures: if, if-else, if-elif-else, while, plus a powerful collection iterator (for).• Multiple levels of organizational structure: functions, classes, modules, and packages. These assist in organizing code. An excellent and large example is the Python standard library.• Compile on the fly to byte code -- Source code is compiled to byte code without a separate compile step. Source code modules can also be "pre-compiled" to byte code files.• Extensions in C and C++ -- Extension modules and extension types can be written by hand. There are also tools that help with this, for example, SWIG, sip, Pyrex.
    4. 4. Getting Python:The most up-to-date and current source code, binaries, documentation, news,etc. is available at the official website of Python:Python Official Website : http://www.python.org/You can download the Python documentation from the following site. Thedocumentation is available in HTML, PDF, and PostScript formats.Python Documentation Website : www.python.org/doc/
    5. 5. On window machine download the Python from the linkhttp://www.python.org/download/releases/2.7.1/Install the software
    6. 6. Select the directory for Python
    7. 7. Select the features to be Installed
    8. 8. Python Shell
    9. 9. Installation on Linux EnvironmentGenerally Python come installed with the Operating SystemBut if it is not available in the installed package , one can installed it by typingthis command on terminal user@ubantu :-$ sudo apt-get install python2.7
    10. 10. Alternate WayUbuntu Linux, the another easiest way to install Python 3 is through the Add/Removeapplication in your Applications menu.Use the Search box immediately after the filter menu to search for Python 3.
    11. 11. Now the list of applications narrows to just those matching Python 3. You’re going tocheck two packages. The first is Python (v3.0). This contains the Python interpreteritself.
    12. 12. The second package you want is immediately above: IDLE (using Python-3.0). Thisis a graphical Python Shell click the Apply Changes button to continue.
    13. 13. The package manager will ask youto confirm that you want to addboth IDLE (using Python-3.0) andPython (v3.0).Click the Apply button to continue.
    14. 14. The package manager will show youa progress meter while it downloadsthe necessary packagesOnce the packages are downloaded,the package manager willautomatically begin installing them.
    15. 15. If all went well, the package manager will confirm that both packages weresuccessfully installed. From here, you can double-click idle to launch the PythonShell, or click the Close button to exit the package manager.You can always re-launch the Python Shell by going to your Applications menu,then the Programming submenu, and selecting idle.
    16. 16. The Python Shell is where you will spend most of your time exploring Python.Examples throughout this book will assume that you can find your way into thePython Shell.
    17. 17. Python leads a dual role in programming• Its an interpreter for scripts that you can run from the command line or run like applications, by double-clicking the scripts.• It can also be use as an interactive shell that can evaluate arbitrary statements and expressions.First Steps in the Interactive Shell>>> 1 + 1 (1)2>>> print hello world (2)hello world>>> x = 1 (3)>>> y = 2>>> x + y3 (1) The Python interactive shell can evaluate arbitrary Python expressions, including any basic arithmetic expression.(2) The interactive shell can execute arbitrary Python statements, including the print statement.(3) You can also assign values to variables, and the values will be remembered as long as the shell is open (but not any longer than that).
    18. 18. Enough to Understand the Code• Assignment uses = and comparison uses ==.• For numbers +-*/% are as expected. – Special use of + for string concatenation. – Special use of % for string formatting.• Logical operators are words (and, or, not) not symbols (&&, ||, !).• The basic printing command is “print.”• First assignment to a variable will create it. – Variable types don’t need to be declared. – Python figures out the variable types on its own.
    19. 19. Whitespace• Whitespace is meaningful in Python: especially indentation and placement of newlines. – Use a newline to end a line of code. (Not a semicolon like in C++ or Java.) (Use when must go to next line prematurely.) – No braces { } to mark blocks of code in Python… Use consistent indentation instead. The first line with a new indentation is considered outside of the block. – Often a colon appears at the start of a new block. (We’ll see this later for function and class definitions.)
    20. 20. Comments• Start comments with # – the rest of line is ignored.• Can include a “documentation string” as the first line of any new function or class that you define.• The development environment, debugger, and other tools use it: it’s good style to include one. def my_function(x, y): “““This is the docstring. This function does blah blah blah.””” # The code would go here...
    21. 21. Variables and types• Variables are created when they are assigned• No declaration required• The variable name is case sensitive: ‘val’ is not the same as ‘Val’• The type of the variable is determined by Python• A variable can be reassigned to whatever, whenever >>> n = 12 >>> print n >>> n = apa 12 >>> print n >>> type(n) apa <type int> >>> type(n) <type str> >>> n = 12.0 >>> type(n) <type float>
    22. 22. Numbers• Integers: 12 0 -12987 0123 0X1A2 – Type ‘int’ – Can’t be larger than 2**31 – Octal literals begin with 0 (0981 illegal!) – Hex literals begin with 0X, contain 0-9 and A-F• Floating point: 12.03 1E1 -1.54E-21 – Type ‘float’ – Same precision and magnitude as C double• Long integers: 10294L – Type ‘long’ – Any magnitude – Python usually handles conversions from int to long• Complex numbers: 1+3J – Type ‘complex’
    23. 23. Numeric expressions• The usual numeric expression operators: +, -, /, *, **, %, //• Precedence and parentheses work as expected >>> 12+5 >>> 4 + 5.5 17 9.5 >>> 12+5*2 >>> 1 + 3.0**2 22 10.0 >>> (12+5)*2 >>> 1+2j + 3-4j 34 (4-2j)>>> a=12+5>>> print a17>>> b = 12.4 + a # a converted to float automatically>>> b29.399999999999999>>> print b 29.4
    24. 24. Boolean expressions• ‘True’ and ‘ False’ are predefined values; actually integers 1 and 0• Value 0 is considered False, all other values True• The usual Boolean expression operators: not, and, or>>> True or FalseTrue>>> not ((True and False) or True)False>>> True * 1212>>> 0 and 10• Comparison operators produce Boolean values• The usual suspects: <, <=, >, >=, ==, !=
    25. 25. String>>> a = Hello world!>>> b = "Hello world!">>> a == bTrue>>> a = "Pers lecture">>> print aPers lecture • Single quotes or double quotes can be used for string literals • Produces exactly the same value • Special characters in string literals: n newline, t tab, others • Triple quotes useful for large chunks of text in program code
    26. 26. String conversions >>> f = float(1.2e-3) >>> f # uses repr 0.0011999999999999999 >>> print f # uses str 0.0012 >>> eval(23-12) 11• Convert data types using functions ‘str’, ‘int’, ‘float’• ‘repr’ is a variant of ‘str’ – intended for strict, code-like representation of values – ‘str’ usually gives nicer-looking representation• Function ‘eval’ interprets a string as a Python expression>>> c =int(blah) #what happens when something illegal #is done?#error messageTraceback (most recent call last): File "<pyshell#34>", line 1, in <module> c = int(blah)ValueError: invalid literal for int(): blah
    27. 27. String operations• Common string operations>>> a = "Part 1">>> b = "and part 2">>> a + + b # concatenation, adding stringsPart 1 and part 2>>> s = a * 2 # repeat and concatenate string>>> print sPart 1Part 1>>> s[0] # index: one single character, offset 0 (zero)P>>> s[0:4] # slice: part of stringPart‘>>> s[5:] # leave out one boundary: to the end1Part 1>>> >>> s[6:-1] # negative index counts from the endPart >>> len(s) # function ‘len’ to get length of string12>>> p in s # membership testFalse>>> P in sTrue>>> Part in s # also works for substrings (new feature)True
    28. 28. Changing strings. Not! >>>s=‘gaurav’ >>> s[0] = B‘ Traceback (most recent call last): File "<pyshell#68>", line 1, in <module> s[0] = B TypeError: object doesnt support item assignment• A string cannot be changed in Python! Immutable• Create new strings from bits and pieces of old• String can not changed but one can create string from another one• Recreating strings may use a lot of computing power• If you need to create many new strings, learn string formatting• List processing can often be used to make string handling more efficient
    29. 29. String methods• Strings have a set of built-in methods• No method ever changes the original string!• Several methods produce new strings• A list on page 91 in ‘Learning Python’>>> s = a string, with stuff>>> s.count(st) # how many substrings?2>>> s.find(stu) # give location of substring, if any15>>> three = 3>>> three.isdigit() # only digit characters in string?True>>> supper = s.upper() # convert to upper case>>> supperA STRING, WITH STUFF>>> s.rjust(30) # right justify by adding blanks a string, with stuff>>> "newlinesnnn".strip() # a string literal also has methods!newlines>>> s.replace(stuff, characters) # replace substring (all occurrences)a string, with characters>>> s.replace(s, X, 1) # replace only oncea Xtring, with stuff
    30. 30. • Lists – e.g. aList = [631, “Programming languages”,[331, “programming languages”]] – List items need not have the same type – Flexible arrays not Lisp-like linked list – Same operators as for strings – More operations append(), insert(), pop(), reverse() and sort()
    31. 31. List>>> r = [1, 2.0, 3, 5] # list literal; different types of values>>> r[1, 2.0, 3, 5]>>> type(r)<type list>>>> r[1] # access by index; offset 0 (zero)2.0>>> r[-1] # negative index counts from end5>>> r[1:3] # a slice out of a list; gives another list[2.0, 3]>>> w = r + [10, 19] # concatenate lists; gives another list>>> w[1, 2.0, 3, 5, 10, 19]>>> r # original list unchanged; w and r are different[1, 2.0, 3, 5]>>> t = [0.0] * 10 # create an initial vector using repetition>>> t[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
    32. 32. List operations• Lists are mutable; can be changed in-place• Lists are dynamic; size may be changed >>> r = [1, 2.0, 3, 5] >>> r[3] = word # replace an item by index >>> r [1, 2.0, 3, word]>>> r[0] = [9, 8] # lists can be nested>>> r[[9, 8], 2.0, 3, word] >>> r[0:3] = [1, 2, 5, 6] # change a slice of list; may change list length >>> r [1, 2, 5, 6, word] >>> r[1:3] = [] # remove items by setting slice to empty list >>> r [1, 6, word] >>> len(r) # length of list; number of items 3 >>> 6 in r # membership test True >>> r.index(6) # search for position; bombs if item not in list 1
    33. 33. List methods, part 1 • Lists have a set of built-in methods • Some methods change the list in-place >>> r = [1, 2.0, 3, 5] >>> r.append(thing) # add a single item to the end >>> r [1, 2.0, 3, 5, thing] >>> r.append([another, list]) # list treated as a single item >>> r [1, 2.0, 3, 5, thing, [another, list]] >>> r = [1, 2.0, 3, 5] >>> r.extend([item, another]) # list items appended one by one >>> r [1, 2.0, 3, 5, item, another] >>> k = r.pop() # remove last item from list and return >>> k another >>> r [1, 2.0, 3, 5, item]• Methods append and pop can be used to implement a stack
    34. 34. List methods, part 2• Use the built-in sort method: efficient• The list is sorted in-place; a new list is not produced!>>> w = [apa, 1, 2, 1234]>>> w.sort() # strings: lexical sort using ASCII order>>> w[1, 1234, 2, apa]>>> w.reverse() # how to flip a list; in-place!>>> w[apa, 2, 1234, 1]>>> v = w[:] # first create a copy of the list>>> v.reverse() # then reverse the copy>>> v # use same technique for sort[1, 1234, 2, apa]>>> w[apa, 2, 1234, 1]
    35. 35. Converting lists between strings>>> s = biovitrum # create a string>>> w = list(s) # convert into a list of chars>>> w[b, i, o, v, i, t, r, u, m]>>> w.reverse()>>> w[m, u, r, t, i, v, o, i, b]>>> r = .join(w) # join using empty string>>> rmurtivoib>>> d = -.join(w) # join using dash char>>> dm-u-r-t-i-v-o-i-b>>> s = a few words>>> w = s.split() # splits at white-space (blank, newline)>>> w[a, few, words] • split is useful for simple parsing • Otherwise use regular expression module re; later
    36. 36. Dictionary • An unordered collection of key/value pairs • Each key maps to a value • Also called "mapping", "hash table" or "lookup table">>> h = {key: 12, nyckel: word}>>> h[key] # access by key12>>> h.has_key(nyckel)True>>> h[Per] = Kraulis # adding a key/value>>> h{nyckel: word, Per: Kraulis, key: 12} # the output order is random>>> h[Per] = Johansson # replaces the value>>> h{nyckel: word, Per: Johansson, key: 12}• The key is – Usually an integer or a string – Should (must!) be an immutable object – May be any object that is hashable’ – Any key occurs at most once in a dictionary!• The value may be any object – Values may occur many times
    37. 37. Dictionary methods, part 1>>> h = {key: 12, nyckel: word}>>> Per in h # test if key in dictionaryFalse>>> h[Per]Traceback (most recent call last): File "<pyshell#192>", line 1, in -toplevel- h[Per]KeyError: Per>>> h.get(Per, unknown) # return value, or default if not foundunknown>>> h.get(key, unknown)12>>> h.keys() # all keys in a list; unordered[nyckel, key]>>> h.values() # all values in a list; unordered[word, 12]>>> len(h) # number of keys in dictionary2
    38. 38. Dictionary methods, part 2>>> g = h.copy() # a separate copy of the dictionary>>> del h[key]>>> h{nyckel: word}>>> g{nyckel: word, key: 12}>>> h[Per] = Johansson>>> h{nyckel: word, Per: Johansson}>>> h.update(g) # add or update all key/value from g>>> h{nyckel: word, key: 12, Per: Johansson}
    39. 39. • Tuples – E.g. aTuple = (631, “Programming Languages”,611, “Computer Architecture”) – Nesting is Possible – Outer Parenthesis is optional – Unlike Lists and like strings tuples are immutable Difference between mutable and immutable types; they handle name assignments differently. If you assign a name to an immutable item, then set a second name equal to the first, changing the value of the first name will not change that of the second. However, for mutable items, changing the value of the first name will change that of the second.
    40. 40. Tuple • Same as list, except immutable • Once created, cant be changed • Some functions return tuples>>> t = (1, 3, 2)>>> t[1] # access by index; offset 0 (zero)3>>> (a, b, c) = t # tuple assignment (unpacking)>>> a1>>> b3>>> a, b, c # actually a tuple expression!(1, 3, 2)>>> a, b = b, a # neat trick to swap values>>> a, b(3, 1)>>> r = list(t) # convert tuple to a list>>> r[1, 3, 2]>>> tuple(r) # convert list to a tuple(1, 3, 2)
    41. 41. Data Type Wrap Up• Lists, Tuples, and Dictionaries can store any type (including other lists, tuples, and dictionaries!)• Only lists and dictionaries are mutable• All variables are references
    42. 42. IDLE ("Interactive Development Environment")Now we need to write proper scripts, saved in filesIn IDLE: File New Window Do immediately Save as… Browse to directory where you want to save your programs Create a directory Python course Go down into it Enter the file name t1.py SaveWork in the window called ‘hello.py Enter the following code: #hello.py # Get the user name and print a friendly Hello name =raw_input("Please enter your name : ") print "Hello", name, "--Good to see U here !" Save the file: Ctrl-S, or menu File, Save Run the script: F5, or menu Run, Run Module
    43. 43. if statement; block structure• The Python feature that one either loves or hates• Block structure is determined by indentation• Edit a new script file t2.py – In window ‘hello.py do File, New Window, then Save As…• Use the if statement:#file t2.pyperson = Luke’if person == Per: status = Pythonistelif person == Luke: status = Jedi knightelse: status = unknown’print person, status• Note that the IDLE editor helps with indentation• Run the script (F5)
    44. 44. for statement• Repetition of a block of statements• Iterate through a sequence (list, tuple, string, iterator)#t3.pys=0for i in [0, 1, 2, 3, 4, 5, 6, 7, 8]: # walk through list, assign to i s=s+i if s > 10: break # quit for loop, jump to after itprint "i=%i, s=%i" % (i, s) Output : i=5, s=15#t4.pyr = []for c in this is a string with blanks: # walks through string, char by char if c == : continue # skip rest of block, continue loop r.append(c)print .join(r)>>> ====================== RESTART===============>>>thisisastringwithblanks
    45. 45. Built-in functions range and xrange’ • Built-in functions range and xrange useful with for • range creates a list • Warning: may use lots of memory; inefficient! >>> range(9) # start=0, step=1 by default [0, 1, 2, 3, 4, 5, 6, 7, 8] >>> range(1, 12, 3) # explicit start, end, step [1, 4, 7, 10] >>> range(10**9) # MemoryError!• xrange creates an iterator, which works like a list• Very memory-efficient! # t5.py” s=0 for i in xrange(100000): if i % 19 == 0: # remainder: evenly divisible with 19? s=s+i print s
    46. 46. Usually, function definitions have the following basic structure: def func(args): return valuesRegardless of the arguments, (including the case of no arguments) a function call mustend with parentheses.Functions may be simple one-to-one mappings>>> def f1(x):... return x*(x-1)...>>> f1(3)6They may contain multiple input and/or output variables>>> def f2(x,y):... return x+y, x-y>>> f2(3,2)(5,1)
    47. 47. How to define your own function• Use the def statement• Function body follows; indented!• This is a statement like others – Can be placed basically anywhere – Required: Define the function before calling it#t5.pydef max(x,y) : if x < y : return y else : return xMaximum=max(5,68)print Maximum>>> ============== RESTART ================>>>68
    48. 48. Function features• The value of an argument is not checked for type – Often very useful; overloading without effort – Of course, the function may still bomb if invalid value is given• The documentation string is not required – But strongly encouraged! – Make a habit of writing one (before writing the function code)• A user-defined function has exactly the same status as a built-in function, or a function from another module
    49. 49. Function arguments: fixed• Fixed number of arguments• Associated by order# t6.pydef fixed_args(a, c, b): # note!: order of args #Format arguments into a string and return return "a=%s, b=%s, c=%s" % (a, b, c) # %s converts to stringprint fixed_args(stuff, 1.2, [2, 1])>>> ================ RESTART ================>>>a=stuff, b=[2, 1], c=1.2>>>
    50. 50. Function arguments: variable• List of any number of arguments• Useful when unknown number of arguments needed• The argument values collected into a tuple – Called args, by convention – The ’*’ is the magical part #t12.p" def unspec_args(a, *args): # name args is a convention return "a=%s, others=%s" % (a, args) print unspec_args(bla, qwe, 23, False)>>> =================== RESTART ====================>>>a=bla, others=(qwe, 23, False)>>>
    51. 51. Function arguments: default values• Arguments may have default values• When argument not given in a call, default value is used• If no default value, and not given when called: bombs• Use explicit names to override argument order#t8.p"def default_args(a, b=bar, c=13): return "a=%s, b=%s, c=%s" % (a, b, c)print default_args(apa) # uses all default valuesprint default_args(s, b=py) # overrides one default valueprint default_args(c=-26, a=apa) # override argument order>>> ================ RESTART ====================>>>a=apa, b=bar, c=13a=s, b=py, c=13a=apa, b=bar, c=-26>>>
    52. 52. Function arguments: keywords• Keyword/value arguments• The argument values collected into a dictionary – Called kwargs, by convention – The ’**’ is the magical part#t9.py First attempts to match existing argument names –def keyword_args(a, b=bla, **kwargs): return "a=%s, b=%s, kwargs=%s" % (a, b, str(kwargs))print keyword_args(stuff, c=call)print keyword_args(stuff, c=call, b=apa)print keyword_args(c=call, d=12, a=gr)>>> =============== RESTART =====================>>>a=stuff, b=bla, kwargs={c: call}a=stuff, b=apa, kwargs={c: call}a=gr, b=bla, kwargs={c: call, d: 12}>>>
    53. 53. Function arguments: explicit type checking• Use the assert statement• Checks that its Boolean expression is True, else bombs• Can be used for sanity checks anywhere in code• Optional explanatory message (or data)#t10.pydef fixed_args(a, c, b): assert type(a) == type(1), "a must be an integer" return "a=%s, b=%s, c=%s" % (a, b, c)print fixed_args(a, 1.2, [2, 1])Traceback (most recent call last): File "C:/Python27/programs/10.py", line 7, in <module> print fixed_args(a, 1.2, [2, 1]) File "C:/Python27/programs/10.py", line 4, in fixed_args assert type(a) == type(1), "a must be an integer"AssertionError: a must be an integerChange the value of a from ‘a’ to any integer value the program will executewithout error
    54. 54. Function arguments: local variables• Arguments become local variables – Immutable values are copied, in effect – Mutable values may still be changed: be careful• Variables created within def block are local – Forgotten on return#t16.pydef test_local(a, r): print local original , a, r a = 12 r[1] = 999 print local changed , a, r a = -5 r = [0, 1, 2] print global original, a, r test_local(a, r) print global changed , a, r>>> ========= RESTART ==============>>>global original -5 [0, 1, 2]local original -5 [0, 1, 2]local changed 12 [0, 999, 2]global changed -5 [0, 999, 2]
    55. 55. Function without return: value None• A function does not have to use the return statement• If not, then same as a procedure in other languages• Actually returns a value anyway: None• A return without value is OK: returns None• None is a special value meaning nothing – Useful in many contexts – Particularly in object-oriented programming (more later)#t17.pydef concat_strings(a, b): str_type = type() # save a type value! if type(a) == str_type and type(b) == str_type: return a + + bprint strings:, concat_strings(first, second)print integers:, concat_strings(1, 2)>>> =============== RESTART ==================>>>strings: first secondintegers: None>>>
    56. 56. Defining a ClassA class is a special data type which defines how to build a certain kind ofobject. The class also stores some data items that are shared by all the instances of this class. Instances are objects that are created which follow the definition given inside of the class.Python doesn’t use separate class interface definitions as in somelanguages. You just define the class and then use it.
    57. 57. Object oriented approachEverything in Python is really an object. We’ve seen hints of this already… “hello”.upper() list3.append(‘a’) dict2.keys() These look like Java or C++ method calls. New object classes can easily be defined in addition to these built- in data-types.In fact, programming in Python is typically done in an object orientedfashion.
    58. 58. Methods in ClassesDefine a method in a class by including function definitions within the scope of theclass block. There must be a special first argument self in all method definitions which gets bound to the calling instance There is usually a special method called __init__ in most classes We’ll talk about both later A simple class definition: student class student: “““A class representing a student.””” def __init__(self,n,a): self.full_name = n self.age = a def get_age(self): return self.age
    59. 59. Instantiating Objects• There is no “new” keyword as in Java.• Merely use the class name with () notation and assign the result to a variable.• __init__ serves as a constructor for the class. Usually does some initialization work.• The arguments passed to the class name are given to its __init__() method. So, the __init__ method for student is passed “Bob” and 21 here and the new class instance is bound to b: b = student(“Bob”, 21)Constructor: __init__ An __init__ method can take any number of arguments. Like other functions or methods, the arguments can be defined with default values, making them optional to the caller. However, the first argument self in the definition of __init__ is special…
    60. 60. class Worker: def __init__(self, name, pay): >>> ========= RESTART========== self.name = name >>> self.pay = pay A B def lastName(self): 66000.0 return self.name.split( )[-1] >>> def giveRaise(self, percent): self.pay *= (1.0 + percent )bob = Worker(A, 50000)sue = Worker(B, 60000)print bob.lastName( )print sue.lastName( )sue.giveRaise(.10)print sue.pay
    61. 61. InheritanceSubclassesA class can extend the definition of another class Allows use (or extension ) of methods and attributes already defined in the previous one. New class: subclass. Original: parent, ancestor or superclassTo define a subclass, put the name of the superclass in parenthesesafter the subclass’s name on the first line of the definition.class ai_student(student): Python has no ‘extends’ keyword like Java. Multiple inheritance is supported.
    62. 62. Redefining MethodsTo redefine a method of the parent class, include a newdefinition using the same name in the subclass. The old code won’t get executed.To execute the method in the parent class in addition tonew code for some method, explicitly call the parent’sversion of the method. parentClass.methodName(self, a, b, c) The only time you ever explicitly pass ‘self’ as an argument is when calling a method of an ancestor.
    63. 63. Definition of a class extending studentclass student:“A class representing a student.” def __init__(self,n,a): self.full_name = n self.age = a def get_age(self): return self.age-------------------------------------------------------------------class ai_student (student):“A class extending student.”def __init__(self,n,a,s): student.__init__(self,n,a) #Call __init__ for student self.section_num = sdef get_age(): #Redefines get_age method entirely print “Age: ” + str(self.age)
    64. 64. Importing and ModulesUse classes & functions defined in another file.A Python module is a file with the same name (plus the .py extension)Like Java import, C++ include.Three formats of the command: import somefile from somefile import * from somefile import classNameWhat’s the difference? What gets imported from the file and what name refers to it after it has been imported.
    65. 65. import …import somefileEverything in somefile.py gets imported.To refer to something in the file, append the text “somefile.” to the front of its name:somefile.className.method(“abc”)somefile.myFunction(34)from … import *from somefile import *Everything in somefile.py gets importedTo refer to anything in the module, just use its name. Everything in the module is now in the current namespace.Caveat! Using this import command can easily overwrite the definition of an existing function or variable!className.method(“abc”)myFunction(34)
    66. 66. from … import …from somefile import classNameOnly the item className in somefile.py gets imported.After importing className, you can just use it without a module prefix. It’s brought into the current namespace.Caveat! This will overwrite the definition of this particular name if it is already defined in the current namespace!className.method(“abc”)  This got imported by this command.myFunction(34)  This one didn’t.
    67. 67. Commonly Used ModulesSome useful modules to import, included with Python:Module: sys - Lots of handy stuff. MaxintModule: os - OS specific code.Module: os.path - Directory processingModule: math - Mathematical code. Exponents SqrtModule: Random - Random number code. Randrange Uniform Choice ShuffleDefining your own modules You can save your own code files (modules) and import them into Python.
    68. 68. There are still a lot to cover in python Tutorial…….But you can get the tutorial from following websites…http://docs.python.org/tutorial/http://diveintopython.org/http://www.rexx.com/~dkuhlman/python_101/python_101.htmlhttp://en.wikibooks.org/wiki/Non-programmer%27s_Tutorial_for_Python_2.6/Example can be read from the sitehttp://www.java2s.com/Code/Python/CatalogPython.html

    ×