Scripts and Utilities -- Python lecture


  • Brad Vander Zanden
  • Directory: /home/cs494/notes/Python
  • This file: http://www.cs.utk.edu/~plank/plank/classes/cs494/494/notes/Python/lecture.html
  • Lecture links: http://www.cs.utk.edu/~plank/plank/classes/cs494/494/notes/Python/links.html
  • Python manuals: http://tecfa.unige.ch/guides/python (This lecture is taken from the Python tutorial manual)
  • Email questions and answers

    Getting Started With Python

    python
    

    Using Python as a Calculator

    >>> 10 + 20
    30
    >>> (40 + 50) * 6 - 10
    530
    >>> 7/3
    2
    >>> 7.0 / 3
    2.33333333333
    

    Results can be assigned to variables using the = sign:

    >>> a = 10 + 30
    >>> a
    40
    >>> b = a * 20
    >>> b
    800
    

    Other Python Data Types

    Strings

    >>> 'spam eggs'
    'spam eggs'
    >>> 'doesn\'t'
    "doesn't"
    >>> "doesn't"
    "doesn't"
    >>> '"Yes, " he said.'
    '"Yes, " he said.'
    >>> "\"Yes, \" he said."
    '"Yes, " he said.'
    

    Strings can be concatenated using the + operator and repeated using the * operator:

    >>> word = 'Help' + 'A'
    >>> word
    'HelpA''
    >>> '<' + word*5 + '>'
    ''
    

    Strings can be subscripted like arrays, with index 0 denoting the first character in the string:

    >>> word[4]
    'A'
    
    Indices may also be negative numbers, to start counting from the right. -1 denotes the last character in the string, -2 the next to last character, and so on:
    >>> word[-1]
    'A'
    >>> word[-2]
    'p'
    
    Python also provides a slicing mechanism that allows you to easily manipulate substrings. A slice is written as two inidces separated by a colon:
    >>> word[0:2]
    'He'
    >>> word [2:4]
    'lp'
    
    If you omit the first index it defaults to 0. If you omit the second index, it defaults to the length of the string:
    >>> word[:2]
    'He'
    >>> word[2:]
    'lpA'
    

    len returns the length of a string:

    >>> len(word)
    5
    

    Strings are immutable so trying to modify an element of a string will result in an error:

    >>> word[3] = 'a'
    Traceback (innermost last):
      File "", line 1, in ?
    TypeError: can't assign to this subscripted object
    

    Lists

    >>> a = [10, 20, 'brad', 'knoxville']
    >>> a
    [10, 20, 'brad', 'knoxville']
    >>> a[1]
    20
    >>> a[1:3]
    [20, 'brad']
    >>> a[-1]
    'knoxville'
    
    The subscripting rules for lists are identical to the subscripting rules for strings.

    Unlike strings, lists can be modified:

    >>> a[1] = 50
    >>> a
    [10, 50, 'brad', 'knoxville']
    >>> a[1:3] = [80, 'hello']
    >>> a
    [10, 80, 'hello', 'knoxville']
    >>> a[0:1] = [20, 60, 70]    # lists can be expanded or shrunk
    [20, 60, 70, 80, 'hello', 'knoxville']
    

    Dictionaries

    >>> tel = {'jack': 4098, 'sape': 4139}
    >>> tel['guido'] = 4127
    >>> tel
    {'sape': 4139, 'guido': 4127, 'jack': 4098}
    >>> tel['jack']
    4098
    >>> del tel['sape']
    >>> tel['irv'] = 4127
    >>> tel
    {'guido': 4127, 'irv': 4127, 'jack': 4098}
    >>> tel.keys()
    ['guido', 'irv', 'jack']
    >>> tel.has_key('guido')
    1
    >>>
    

    Control Flow Tools

    Conditionals

    >>> if x < 0:
    ...      x = 0
    ...      print 'Negative changed to zero'
    ... elif x == 0:
    ...      print 'Zero'
    ... elif x == 1:
    ...      print 'Single'
    ... else:
    ...      print 'More'
    

    Loops

    For Loops

    >>> # Measure some strings:
        a = ['cat', 'window', 'defenestrate']
    >>> for x in a:
            print x, len(x)
    >>>
    

    How to insert items into a list--It is not safe to insert into a list while iterating over it:

    >>> for x in a[:]: # make a slice copy of the entire list
            if len(x) > 6: a.insert(0, x)
    
    >>> a
    ['defenestrate', 'cat', 'window', 'defenestrate']
    >>>
    

    >>> sum = 0
    >>> for i in range(10):
            sum = sum + i
    >>> print sum
    

    While Loop

    >>> a = range(10)
    >>> i = 0
    >>> while (i < 10):
    ...     if a[i] == 5:
    ...	    print i
    ...	    break
    ...     else:
    ...	    i = i + 1
    ... else:
    ...     print 'could not find 5'
    

    Functions

    >>> true = 1
    >>> false = 0
    
    >>> def dfs(node):
    ...    node.visited = true
    ...    for neighbor in node.neighbors:
    ...	   if neighbor.visited == false:
    ...	       dfs(neighbor)
    

    Classes

    >>> class node:
    ...     pass
    

    Without initialization function:

    >>> x = node()
    >>> x.visited = false
    >>> x.neighbors = []
    

    With initialization function:

    >>> class node:
    ...    def __init__(self):
    ...        self.visited = false
    ...  	   self.neighbors = []
    
    >>> x = node()