SlideShare une entreprise Scribd logo
1  sur  82
A Brief Introduction

  “Python is an interpreted, interactive, object-oriented
    programming language...

  •    Python is Interpreted
  •    Python is Interactive
  •    Python is Object-Oriented
  •    Python is Beginner's 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
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.
• 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.
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. The
documentation is available in HTML, PDF, and PostScript formats.
Python Documentation Website :

                           www.python.org/doc/
On window machine download the Python from the link
http://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 Environment
Generally Python come installed with the Operating System
But if it is not available in the installed package , one can installed it by typing
this command on terminal
      user@ubantu :-$ sudo apt-get install python2.7
Alternate Way

Ubuntu Linux, the another easiest way to install Python 3 is through the Add/Remove
application in your Applications menu.
Use the Search box immediately after the filter menu to search for Python 3.
Now the list of applications narrows to just those matching Python 3. You’re going to
check two packages. The first is Python (v3.0). This contains the Python interpreter
itself.
The second package you want is immediately above: IDLE (using Python-3.0). This
is a graphical Python Shell




   click the Apply Changes button to continue.
The package manager will ask you
to confirm that you want to add
both IDLE (using Python-3.0) and
Python (v3.0).




Click the Apply button to continue.
The package manager will show you
a progress meter while it downloads
the necessary packages




Once the packages are downloaded,
the package manager will
automatically begin installing them.
If all went well, the package manager will confirm that both packages were
successfully installed. From here, you can double-click idle to launch the Python
Shell, 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.
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 the
Python Shell.
Python leads a dual role in programming
• It's 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 + y
3
 (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).
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.
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.)
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...
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'>
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’
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 a
17
>>> b = 12.4 + a   # 'a' converted to float automatically
>>> b
29.399999999999999
>>> print b      '
29.4
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 False
True
>>> not ((True and False) or True)
False
>>> True * 12
12
>>> 0 and 1
0

•   Comparison operators produce Boolean values
•   The usual suspects: <, <=, >, >=, ==, !=
String
>>> a = 'Hello world!'
>>> b = "Hello world!"
>>> a == b
True


>>> a = "Per's lecture"
>>> print a
Per's 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
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 message
Traceback (most recent call last):
 File "<pyshell#34>", line 1, in <module>
  c = int('blah')
ValueError: invalid literal for int(): blah
String operations
•    Common string operations
>>> a = "Part 1"
>>> b = "and part 2"
>>> a + ' ' + b     # concatenation, adding strings
'Part 1 and part 2'
>>> s = a * 2       # repeat and concatenate string
>>> print s
Part 1Part 1


>>> s[0]          # index: one single character, offset 0 (zero)
'P'
>>> s[0:4]        # slice: part of string
'Part‘
>>> s[5:]         # leave out one boundary: to the end
'1Part 1'
>>> >>> s[6:-1]    # negative index counts from the end
'Part '


>>> len(s)        # function ‘len’ to get length of string
12
>>> 'p' in s      # membership test
False
>>> 'P' in s
True
>>> 'Part' in s    # also works for substrings (new feature)
True
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 doesn't 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
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 any
15
>>> three = '3'
>>> three.isdigit()            # only digit characters in string?
True


>>> supper = s.upper()          # convert to upper case
>>> supper
'A 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 once
'a Xtring, with stuff'
• 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()
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 end
5

>>> 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]
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
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
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']
Converting lists between strings
>>> s = 'biovitrum'                            # create a string
>>> w = list(s)                              # convert into a list of char's
>>> 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
>>> r
'murtivoib'
>>> d = '-'.join(w)                            # join using dash char
>>> d
'm-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
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 key
12
>>> 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
Dictionary methods, part 1
>>> h = {'key': 12, 'nyckel': 'word'}
>>> 'Per' in h               # test if key in dictionary
False
>>> 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 found
'unknown'
>>> 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 dictionary
2
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'}
•   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.
Tuple
 •   Same as list, except immutable
 •   Once created, can't 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)
>>> a
1
>>> b
3
>>> 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)
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
IDLE ("Interactive Development Environment")
Now we need to write proper scripts, saved in files
In 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'
           Save
Work 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'
'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.py
person = 'Luke’
if person == 'Per':
   status = 'Pythonist'
elif person == 'Luke':
   status = 'Jedi knight'
else:
   status = 'unknown’
print person, status

•   Note that the IDLE editor helps with indentation
•   Run the script (F5)
'for' statement
•   Repetition of a block of statements
•   Iterate through a sequence (list, tuple, string, iterator)

#t3.py
s=0
for 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 it
print "i=%i, s=%i" % (i, s)

    Output :             i=5, s=15
#t4.py
r = []
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
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
Usually, function definitions have the following basic structure:

   def func(args):
        return values

Regardless of the arguments, (including the case of no arguments) a function call must
end with parentheses.
Functions may be simple one-to-one mappings
>>> def f1(x):
... return x*(x-1)
...
>>> f1(3)
6
They may contain multiple input and/or output variables
>>> def f2(x,y):
... return x+y, x-y

>>> f2(3,2)
(5,1)
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.py

def max(x,y) :
  if x < y :
     return y
  else :
     return x

Maximum=max(5,68)
print Maximum



>>> ============== RESTART ================
>>>
68
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
Function arguments: fixed
•   Fixed number of arguments
•   Associated by order

# t6.py
def 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 string
print fixed_args('stuff', 1.2, [2, 1])


>>> ================ RESTART ================
>>>
a=stuff, b=[2, 1], c=1.2
>>>
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)
>>>
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 values
print default_args('s', b='py')                                # overrides one default value
print default_args(c=-26, a='apa')                             # override argument order

>>> ================ RESTART ====================
>>>
a=apa, b=bar, c=13
a=s, b=py, c=13
a=apa, b=bar, c=-26
>>>
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}
>>>
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.py
def 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 integer

Change the value of a from ‘a’ to any integer value the program will execute
without error
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.py

def 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]
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.py
def concat_strings(a, b):
  str_type = type('')               # save a type value!
  if type(a) == str_type and type(b) == str_type:
     return a + ' ' + b
print 'strings:', concat_strings('first', 'second')
print 'integers:', concat_strings(1, 2)

>>> =============== RESTART ==================
>>>
strings: first second
integers: None
>>>
Defining a Class

A class is a special data type which defines how to build a certain kind of
object.

    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 some
languages. You just define the class and then use it.
Object oriented approach

Everything 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 oriented
fashion.
Methods in Classes
Define a method in a class by including function definitions within the scope of the
class 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
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…
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
Inheritance
Subclasses
A 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 superclass

To define a subclass, put the name of the superclass in parentheses
after 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.
Redefining Methods
To redefine a method of the parent class, include a new
definition using the same name in the subclass.
   The old code won’t get executed.

To execute the method in the parent class in addition to
new code for some method, explicitly call the parent’s
version 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.
Definition of a class extending 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
-------------------------------------------------------------------
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 = s
def get_age(): #Redefines get_age method entirely
  print “Age: ” + str(self.age)
Importing and Modules

Use 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 className


What’s the difference?
   What gets imported from the file and what name refers
   to it after it has been imported.
import …
import somefile

Everything 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 imported
To 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)
from … import …
from somefile import className

Only 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.
Commonly Used Modules

Some useful modules to import, included with Python:
Module: sys               - Lots of handy stuff.
   Maxint
Module: os                - OS specific code.
Module: os.path           - Directory processing
Module: math              - Mathematical code.
   Exponents
   Sqrt
Module: Random            - Random number code.
   Randrange
   Uniform
   Choice
   Shuffle
Defining your own modules
   You can save your own code files (modules) and import them
     into Python.
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.html
http://en.wikibooks.org/wiki/Non-programmer%27s_Tutorial_for_Python_2.6/




Example can be read from the site
http://www.java2s.com/Code/Python/CatalogPython.html
Python

Contenu connexe

Tendances

Tendances (20)

Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
Python list
Python listPython list
Python list
 
Windows form application - C# Training
Windows form application - C# Training Windows form application - C# Training
Windows form application - C# Training
 
Python Programming Essentials - M9 - String Formatting
Python Programming Essentials - M9 - String FormattingPython Programming Essentials - M9 - String Formatting
Python Programming Essentials - M9 - String Formatting
 
Introduction to Python - Training for Kids
Introduction to Python - Training for KidsIntroduction to Python - Training for Kids
Introduction to Python - Training for Kids
 
Presentation on python
Presentation on pythonPresentation on python
Presentation on python
 
Chapter 05 classes and objects
Chapter 05 classes and objectsChapter 05 classes and objects
Chapter 05 classes and objects
 
List in Python
List in PythonList in Python
List in Python
 
Strings in python
Strings in pythonStrings in python
Strings in python
 
Python-04| Fundamental data types vs immutability
Python-04| Fundamental data types vs immutabilityPython-04| Fundamental data types vs immutability
Python-04| Fundamental data types vs immutability
 
Html formatting
Html formattingHtml formatting
Html formatting
 
Object Oriented Programing JAVA presentaion
Object Oriented Programing JAVA presentaionObject Oriented Programing JAVA presentaion
Object Oriented Programing JAVA presentaion
 
Best Python IDEs
Best Python IDEsBest Python IDEs
Best Python IDEs
 
Html forms
Html formsHtml forms
Html forms
 
Programming in c Arrays
Programming in c ArraysProgramming in c Arrays
Programming in c Arrays
 
Python data type
Python data typePython data type
Python data type
 
Functions in python
Functions in pythonFunctions in python
Functions in python
 
Bootstrap
BootstrapBootstrap
Bootstrap
 
Python programming introduction
Python programming introductionPython programming introduction
Python programming introduction
 
Python-Tuples
Python-TuplesPython-Tuples
Python-Tuples
 

Similaire à Python

Similaire à Python (20)

Python course
Python coursePython course
Python course
 
Python ppt
Python pptPython ppt
Python ppt
 
PYTHON
PYTHONPYTHON
PYTHON
 
ENGLISH PYTHON.ppt
ENGLISH PYTHON.pptENGLISH PYTHON.ppt
ENGLISH PYTHON.ppt
 
An Introduction : Python
An Introduction : PythonAn Introduction : Python
An Introduction : Python
 
manish python.pptx
manish python.pptxmanish python.pptx
manish python.pptx
 
python1.ppt
python1.pptpython1.ppt
python1.ppt
 
python1.ppt
python1.pptpython1.ppt
python1.ppt
 
Python Basics
Python BasicsPython Basics
Python Basics
 
python1.ppt
python1.pptpython1.ppt
python1.ppt
 
Lenguaje Python
Lenguaje PythonLenguaje Python
Lenguaje Python
 
pysdasdasdsadsadsadsadsadsadasdasdthon1.ppt
pysdasdasdsadsadsadsadsadsadasdasdthon1.pptpysdasdasdsadsadsadsadsadsadasdasdthon1.ppt
pysdasdasdsadsadsadsadsadsadasdasdthon1.ppt
 
coolstuff.ppt
coolstuff.pptcoolstuff.ppt
coolstuff.ppt
 
python1.ppt
python1.pptpython1.ppt
python1.ppt
 
Introductio_to_python_progamming_ppt.ppt
Introductio_to_python_progamming_ppt.pptIntroductio_to_python_progamming_ppt.ppt
Introductio_to_python_progamming_ppt.ppt
 
python1.ppt
python1.pptpython1.ppt
python1.ppt
 
python1.ppt
python1.pptpython1.ppt
python1.ppt
 
python1.ppt
python1.pptpython1.ppt
python1.ppt
 
Python Scipy Numpy
Python Scipy NumpyPython Scipy Numpy
Python Scipy Numpy
 
Learning python
Learning pythonLearning python
Learning python
 

Plus de Kumar Gaurav

Plus de Kumar Gaurav (6)

Numerical method
Numerical methodNumerical method
Numerical method
 
Cellular network History
Cellular network HistoryCellular network History
Cellular network History
 
Cellular networks
Cellular networksCellular networks
Cellular networks
 
Standard Template Library
Standard Template LibraryStandard Template Library
Standard Template Library
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
J2ME
J2MEJ2ME
J2ME
 

Dernier

Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
Chris Hunter
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 

Dernier (20)

Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Role Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxRole Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptx
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-IIFood Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 

Python

  • 1.
  • 2. A Brief Introduction “Python is an interpreted, interactive, object-oriented programming language... • Python is Interpreted • Python is Interactive • Python is Object-Oriented • Python is Beginner's 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
  • 3.
  • 4. 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.
  • 5. • 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.
  • 6.
  • 7. 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. The documentation is available in HTML, PDF, and PostScript formats. Python Documentation Website : www.python.org/doc/
  • 8. On window machine download the Python from the link http://www.python.org/download/releases/2.7.1/ Install the software
  • 9. Select the directory for Python
  • 10. Select the features to be Installed
  • 11.
  • 12.
  • 14. Installation on Linux Environment Generally Python come installed with the Operating System But if it is not available in the installed package , one can installed it by typing this command on terminal user@ubantu :-$ sudo apt-get install python2.7
  • 15. Alternate Way Ubuntu Linux, the another easiest way to install Python 3 is through the Add/Remove application in your Applications menu. Use the Search box immediately after the filter menu to search for Python 3.
  • 16. Now the list of applications narrows to just those matching Python 3. You’re going to check two packages. The first is Python (v3.0). This contains the Python interpreter itself.
  • 17. The second package you want is immediately above: IDLE (using Python-3.0). This is a graphical Python Shell click the Apply Changes button to continue.
  • 18. The package manager will ask you to confirm that you want to add both IDLE (using Python-3.0) and Python (v3.0). Click the Apply button to continue.
  • 19. The package manager will show you a progress meter while it downloads the necessary packages Once the packages are downloaded, the package manager will automatically begin installing them.
  • 20. If all went well, the package manager will confirm that both packages were successfully installed. From here, you can double-click idle to launch the Python Shell, 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.
  • 21. 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 the Python Shell.
  • 22.
  • 23. Python leads a dual role in programming • It's 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 + y 3 (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).
  • 24. 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.
  • 25. 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.)
  • 26. 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...
  • 27. 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'>
  • 28. 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’
  • 29. 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 a 17 >>> b = 12.4 + a # 'a' converted to float automatically >>> b 29.399999999999999 >>> print b ' 29.4
  • 30. 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 False True >>> not ((True and False) or True) False >>> True * 12 12 >>> 0 and 1 0 • Comparison operators produce Boolean values • The usual suspects: <, <=, >, >=, ==, !=
  • 31. String >>> a = 'Hello world!' >>> b = "Hello world!" >>> a == b True >>> a = "Per's lecture" >>> print a Per's 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
  • 32. 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 message Traceback (most recent call last): File "<pyshell#34>", line 1, in <module> c = int('blah') ValueError: invalid literal for int(): blah
  • 33. String operations • Common string operations >>> a = "Part 1" >>> b = "and part 2" >>> a + ' ' + b # concatenation, adding strings 'Part 1 and part 2' >>> s = a * 2 # repeat and concatenate string >>> print s Part 1Part 1 >>> s[0] # index: one single character, offset 0 (zero) 'P' >>> s[0:4] # slice: part of string 'Part‘ >>> s[5:] # leave out one boundary: to the end '1Part 1' >>> >>> s[6:-1] # negative index counts from the end 'Part ' >>> len(s) # function ‘len’ to get length of string 12 >>> 'p' in s # membership test False >>> 'P' in s True >>> 'Part' in s # also works for substrings (new feature) True
  • 34. 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 doesn't 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
  • 35. 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 any 15 >>> three = '3' >>> three.isdigit() # only digit characters in string? True >>> supper = s.upper() # convert to upper case >>> supper 'A 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 once 'a Xtring, with stuff'
  • 36.
  • 37. • 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()
  • 38. 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 end 5 >>> 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]
  • 39. 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
  • 40. 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
  • 41. 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']
  • 42. Converting lists between strings >>> s = 'biovitrum' # create a string >>> w = list(s) # convert into a list of char's >>> 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 >>> r 'murtivoib' >>> d = '-'.join(w) # join using dash char >>> d 'm-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
  • 43.
  • 44. 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 key 12 >>> 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
  • 45. Dictionary methods, part 1 >>> h = {'key': 12, 'nyckel': 'word'} >>> 'Per' in h # test if key in dictionary False >>> 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 found 'unknown' >>> 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 dictionary 2
  • 46. 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'}
  • 47.
  • 48. 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.
  • 49. Tuple • Same as list, except immutable • Once created, can't 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) >>> a 1 >>> b 3 >>> 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)
  • 50. 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
  • 51.
  • 52. IDLE ("Interactive Development Environment") Now we need to write proper scripts, saved in files In 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' Save Work 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'
  • 53. '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.py person = 'Luke’ if person == 'Per': status = 'Pythonist' elif person == 'Luke': status = 'Jedi knight' else: status = 'unknown’ print person, status • Note that the IDLE editor helps with indentation • Run the script (F5)
  • 54. 'for' statement • Repetition of a block of statements • Iterate through a sequence (list, tuple, string, iterator) #t3.py s=0 for 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 it print "i=%i, s=%i" % (i, s) Output : i=5, s=15 #t4.py r = [] 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
  • 55. 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
  • 56.
  • 57. Usually, function definitions have the following basic structure: def func(args): return values Regardless of the arguments, (including the case of no arguments) a function call must end with parentheses. Functions may be simple one-to-one mappings >>> def f1(x): ... return x*(x-1) ... >>> f1(3) 6 They may contain multiple input and/or output variables >>> def f2(x,y): ... return x+y, x-y >>> f2(3,2) (5,1)
  • 58. 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.py def max(x,y) : if x < y : return y else : return x Maximum=max(5,68) print Maximum >>> ============== RESTART ================ >>> 68
  • 59. 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
  • 60. Function arguments: fixed • Fixed number of arguments • Associated by order # t6.py def 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 string print fixed_args('stuff', 1.2, [2, 1]) >>> ================ RESTART ================ >>> a=stuff, b=[2, 1], c=1.2 >>>
  • 61. 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) >>>
  • 62. 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 values print default_args('s', b='py') # overrides one default value print default_args(c=-26, a='apa') # override argument order >>> ================ RESTART ==================== >>> a=apa, b=bar, c=13 a=s, b=py, c=13 a=apa, b=bar, c=-26 >>>
  • 63. 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} >>>
  • 64. 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.py def 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 integer Change the value of a from ‘a’ to any integer value the program will execute without error
  • 65. 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.py def 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]
  • 66. 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.py def concat_strings(a, b): str_type = type('') # save a type value! if type(a) == str_type and type(b) == str_type: return a + ' ' + b print 'strings:', concat_strings('first', 'second') print 'integers:', concat_strings(1, 2) >>> =============== RESTART ================== >>> strings: first second integers: None >>>
  • 67.
  • 68. Defining a Class A class is a special data type which defines how to build a certain kind of object. 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 some languages. You just define the class and then use it.
  • 69. Object oriented approach Everything 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 oriented fashion.
  • 70. Methods in Classes Define a method in a class by including function definitions within the scope of the class 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
  • 71. 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…
  • 72. 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
  • 73. Inheritance Subclasses A 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 superclass To define a subclass, put the name of the superclass in parentheses after 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.
  • 74. Redefining Methods To redefine a method of the parent class, include a new definition using the same name in the subclass. The old code won’t get executed. To execute the method in the parent class in addition to new code for some method, explicitly call the parent’s version 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.
  • 75. Definition of a class extending 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 ------------------------------------------------------------------- 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 = s def get_age(): #Redefines get_age method entirely print “Age: ” + str(self.age)
  • 76.
  • 77. Importing and Modules Use 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 className What’s the difference? What gets imported from the file and what name refers to it after it has been imported.
  • 78. import … import somefile Everything 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 imported To 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)
  • 79. from … import … from somefile import className Only 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.
  • 80. Commonly Used Modules Some useful modules to import, included with Python: Module: sys - Lots of handy stuff. Maxint Module: os - OS specific code. Module: os.path - Directory processing Module: math - Mathematical code. Exponents Sqrt Module: Random - Random number code. Randrange Uniform Choice Shuffle Defining your own modules You can save your own code files (modules) and import them into Python.
  • 81. 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.html http://en.wikibooks.org/wiki/Non-programmer%27s_Tutorial_for_Python_2.6/ Example can be read from the site http://www.java2s.com/Code/Python/CatalogPython.html

Notes de l'éditeur

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