Native Types in Python ---------------------------------------- * Numbers * Strings * Lists * Tuples * Sets * Dictionaries * Built-in Constants Numbers ---------------------------------------- Do I really need to tell you about numbers? Integers ---------------------------------------- Plain integers and long integers are unified in Python. You don't need to worry about overflow as it will convert to a long automatically. .. code-block:: python import sys a = sys.maxint print a b = a*2 print b Integers (cont.) ---------------------------------------- Integer literals are interpreted as plain integers unless they don't fit in which case they are automatically converted to longs. You can force a literal to be a long by using 'l' or 'L' as a suffix. .. code-block:: python a = 100000000000000000000000000000000000 print a b = 10 print b b = 10L print b Floats ---------------------------------------- Floats are implemented as a double in the underlying C. You can see the underlying precision using sys.float_info .. code-block:: python import sys print sys.float_info Some Notes on Division ---------------------------------------- Integer division returns the floor. If you want to avoid that you can explicitly convert to a float. Converting after the division is too late. .. code-block:: python a = 7 b = 2 print a / b print float(a) / b print float(a / b) Python 3 Note ---------------------------------------- Integer division no longer returns the floor. You can recreate this behavior in Python 2.6 by importing from the ``__future__`` module. .. code-block:: python from __future__ import division a = 7 b = 2 print a / b Complex Numbers ---------------------------------------- Real and imaginary parts are both stored as floats. Imaginary literals can be created using a 'j' or 'J' suffix or with the complex() function. .. code-block:: python a = 1 + 1j print a.conjugate() print complex(2, 5) print a**2 print a.real print a.imag Complex Math ---------------------------------------- The ``math`` module only supports types which can be converted to floats. For math functions which work with complex numbers use the ``cmath`` module. .. code-block:: python import cmath a = 1 + 1j print cmath.log(a) print cmath.sqrt(a) Strings ---------------------------------------- Strings are a sequence type to hold character data. String literals can be enclosed in ' or " characters. The backslash character is an escape character. .. code-block:: python a = 'blip' # The string blip b = "blip" # The string blah Raw Strings ---------------------------------------- Strings can also be marked as raw strings with a r/R in which case the escape character is not needed. .. code-block:: python a = '\n' # newline character print a b = r'\n' # the string \n print b Triple Quoted Strings ---------------------------------------- We've seens triple quoted strings used as comments. They define string literals which can span more than one line and include the newline characters. .. code-block:: python a = """ This string is on multiple lines. It can be very long if you wish. """ Strings are Immutable ---------------------------------------- Unlike C, Strings are immutable meaning you cannot change them once they are created. .. code-block:: python a = 'My test string' print a[0] a[0] = 'b' # This will generate an error. Basic String Formatting ---------------------------------------- Python uses the same string formatting as ``printf`` in C. - 'd' Signed integer decimal. - 'i' Signed integer decimal. - 'o' Signed octal value. - 'x' Signed hexadecimal (lowercase). - 'X' Signed hexadecimal (uppercase). - 'e' Floating point exponential format (lowercase). - 'E' Floating point exponential format (uppercase). - 'f' Floating point decimal format. - 'F' Floating point decimal format. - 'r' String (converts any Python object using repr()). - 's' String (converts any Python object using str()). String Formatting Examples ---------------------------------------- .. code-block:: python a = 10 b = 37.0 print '%i %i' % (a, b) print '%f %f' % (a, b) print '%s %s' % (a, b) Formatting with Mappings ---------------------------------------- You can also used named mappings while formatting strings. .. code-block:: python print '%(last)s, %(first)s' % {'first': 'Mark', 'last': 'Lavin'} More on mappings coming up. String Formatting in Python 3 ---------------------------------------- Python 2.6 includes a back-port of new style string formatting as defined by `PEP 3101 `_. .. code-block:: python # positional arguments '{0} {1}'.format('Hello', 'World') # named arguments '{first} {second}'.format(second='World', first='Hello') String Concatenating ---------------------------------------- Stings can be combined with the + operator or by using string formatting. Note that the + operator will not change type. .. code-block:: python a = 'test' b = 'string' c = 10 print a + b print '%s %s' % (a, b) print a + c # This will produce an error print '%s %s' % (a, c) String Methods ---------------------------------------- There are a number of handy string methods built in. Remeber because strings are immutable they return a new string rather than modifying the calling string. .. code-block:: python a = 'my test string' print a.upper() print a String Methods Listing ---------------------------------------- .. code-block:: python 'test'.capitalize() # returns 'Test' 'test'.endswith('a') # returns False 'test'.find('e') # returns 1 (would return -1 if not found) 'test'.lower() # returns 'test' 'test'.replace('t', 'b') # returns 'besb' 'a b c'.split() # returns ['a', 'b', 'c'] 'test'.startswith('i') # returns False 'test string'.title() # returns 'Test String' 'test'.upper() # returns 'TEST' Check out the full list here: http://docs.python.org/library/stdtypes.html#string-methods Lists ---------------------------------------- List define a zero-indexed squence of objects. .. code-block:: python a = [1, 2, 3] Items in a list do not need to be the same type. Lists can also be nested. .. code-block:: python a = [1, 'a', [2, 'b']] Accessing List Items ---------------------------------------- Accessing items in a list is done with a bracket syntax. You can access one or more index at a time. You can also use negative indexes. .. code-block:: python a = [1, 2, 3] print a[0] print a[0:1] print a[-1] Lists Functions ---------------------------------------- .. code-block:: python [1, 2, 3].append(4) # Inserts value at the end of the list [1, 2, 3].extend([4, 5]) # Appends iterable to the end of the list [1, 2, 3].pop() # Returns first item and removes from the list [1, 2, 3].count(1) # Returns the number of values which match [1, 2, 3].index(2) # Returns the first index where value is found [1, 2, 3].insert(1, 4) # Inserts 4 to position 1 [1, 2, 3].reverse() # Reverses the order of items Check out the full list here: http://docs.python.org/library/stdtypes.html#mutable-sequence-types List as a Stack ---------------------------------------- It's easy to use Python lists as a stack (last-in, first-out). .. code-block:: python a = [1, 2, 3] a.append(4) print a print a.pop() print a print a.pop() print a Tuples ---------------------------------------- Tuples are similar to lists but with one large difference. Tuples are immutable meaning you cannot change their values once they are set. Tuples use a parentheses rather than a bracket. .. code-block:: python a = (1, 2, 3) Beware of the Trailing Comma ---------------------------------------- Parentheses around a tuple are optional. This allows for handy things like swapping values and unpacking tuples or lists. But if you type .. code-block:: python a = 1, # a is a tuple (1,) Unpacking Lists and Tuples ---------------------------------------- It's possible to unpack a list or tuple: .. code-block:: python a, b, c = [1, 2, 3] print a print b print c Simple Variable Swap ---------------------------------------- Using a similar syntax you can easily swap to variables: .. code-block:: python a = 1 b = 2 a, b = b, a print a print b Dictionaries ---------------------------------------- Dictionaries are key-value mappings. In other contexts or languages they are called associative arrays or maps. They are defined by .. code-block:: python a = {'key': 'value'} a['key'] a['new-key'] = 'new-value' Using Dictionaries ---------------------------------------- You check if a key is in a dictionary using in or use get to return a default value if the key does not exist. Trying to access a key which does not exist raise a KeyError .. code-block:: python if 'key' in a: print a['key'] print a.get('key') # returns None if not found print a.get('key', 1) # returns 1 if not found Using Dictionaries (cont.) ---------------------------------------- You can access all of the keys in a dictionary with the ``keys`` function. You can access a list of all values using the ``values`` function. You can also iterate over all the key, value pairs using ``iteritems``. .. code-block:: python a = {'1': 'a', '2': 'b'} print a.keys() print a.values() for k,v in a.iteritems(): print 'Key %s' % k print 'Value %s' % v Sets ---------------------------------------- Sets in Python are much like sets in mathematics. They are an un-ordered collection of objects without duplicates. This allows for fast membership detection as well as familiar set operations. .. code-block:: python a = set([1, 2, 3]) b = set([2, 4, 6]) a | b # union a & b # intersection a - b # difference a ^ b # symmetric difference Set Comparsions ---------------------------------------- Comparison operators can be used to check for subsets. .. code-block:: python a = set([1, 2, 3]) b = set([1 ,2, 3, 6]) a <= b # Is subset? a < b # Is strict (non-equal) subset a >= b # Is superset? a > b # Is strict (non-equal) superset Sets in Python 3.X ---------------------------------------- While in Python 2.X you must use the ``set()`` function to create sets, Python 3 allows for set literals using a brace syntax. .. code-block:: python a = {1, 2, 3} Note that ``{}`` is still an dictionary. Unpacking Positional Arguments ---------------------------------------- Lists and tuples can be unpacked to fill in positional arguments for a function call using \*. .. code-block:: python def add(x, y): return x + y data = (1, 2) print add(*data) Unpacking Keyword Arguments ---------------------------------------- Dictionaries can be used to fill arguments using \**. .. code-block:: python def subtract(x, y): return x - y data = {'y': 1, 'x': 3} print subtract(**data) # same as subtract(y=1, x=3) Built-in Constants ---------------------------------------- Python has built in logical constants. .. code-block:: python True, False, None Notes on Truth ---------------------------------------- The built-in ``bool`` function is used to convert other types to either ``True`` or ``False``. For the most part everything in Python is ``True`` except for various empty values. .. code-block:: python # False values 0, 0.0 # Zero '', "" # Empty strings [], () # Empty lists and tuples {}, None # Empty dictionaries and None Up Next ---------------------------------------- Creating your own classes! .. header:: MA792K Spring 2011 Lecture 2 .. footer:: © Mark Lavin 2011