Chapter 3. First steps in Python
Table of Contents
This really isn't even an introduction --- it's just to get a taste of the interpreter, and of how some basic Python data types look.
Python is an interpreted language. To use it, start up the interpreter and begin typing commands at the interactive prompt.
Python has four distinct numeric types, namely: plain integers, long integers, floating point numbers and complex numbers.
Numbers are created by numeric literals or by using built-in constructors, namely: int(), long(), float(), complex().
>>>x = 1 # assigns an integer to 'x'
>>>x = int('1') # integer created using builtin constructor
>>>
>>>x = 1.0 # assigns a float to 'x'
>>>x = float('1.0') # float created using builtin constructor
Python supports mixed arithmetic, so multiplying an integer with a number is allowed:
>>>1 * 2.0 >>>2.0
Strings are written by enclosing text in single or double quotes:
>>>name = 'Pete' >>>surname = "O'Reilly"
Quotes in strings can be escaped by using a backslash:
>>>s = 'don\'t'
Backslashes are also used for line continuation:
>>>sentence = 'This is a very long string that \ >>>continues on the next line'
A pair of matching triple-quotes can be used for very long strings without escaping line ends.
>>>sentence = '''This is a very long string that >>>continues on the next line'''
Python supports operator overloading, and most operators are implemented for any data type where they make sense. For example:
Strings can be concatenated by using the + operator:
>>>fullname = 'Pete' + ' ' + 'Smith' >>>fullname 'Pete Smith'
Multiplication works:
>>>petes = fullname * 5 >>>fullname 'Pete SmithPete SmithPete SmithPete SmithPete Smith'
.. but only where it makes sense:
>>> 'a'*'b' Traceback (most recent call last): File "<stdin<", line 1, in ? TypeError: unsupported operand type(s) for *: 'str' and 'str'
This can easily become too magic, so be careful of too much operator overloading.
String literals next to each other are automatically concatenated:
>>>fullname = 'Pete ' 'Smith' >>>fullname 'Pete Smith'
Strings are indexed and can be subscripted or sliced. Strings are subscripted by specifying the index of the character to return:
>>>fullname[0] 'P' >>>fullname[1] 'e'
Substrings are specified by using slice notation:
>>>fullname[0:4] 'Pete'
Omitting the first index defaults to zero, and omitting the second defaults to the size of the string:
>>>fullname[:4] 'Pete' >>>fullname[5:] 'Smith'
Lists are written as a list of comma-separated values between square brackets:
>>>fruit = ['apple', 'pear', 'banana'] >>>fruit ['apple', 'pear', 'banana']
Like with strings, lists can be concatenated, sliced and subscripted:
>>>fruit[0] 'apple' >>>fruit[0:1] ['apple', 'pear'] >>>fruit + ['apricot'] ['apple', 'pear', 'banana', 'apricot']
Lists are mutable (strings are not) and items in a list can be modified:
>>>fruit[0] = 'strawberry' >>>fruit ['strawberry', 'pear', 'banana', 'apricot'] >>>fruit[0:1] = ['apple', 'cranberry'] >>>fruit ['apple', 'cranberry', 'banana', 'apricot']
Lists provide numerous functions with which to manipulate them. Some are append, extend, insert, pop, remove, reverse, sort. These functions are available as methods of list instances (and this clearly illustrates how everything in Python is an object):
>>>fruit = ['apple', 'pear']
>>>fruit.append('banana') # adds item to list
>>>fruit
['apple', 'pear', 'banana']
>>>fruit.extend(['cranberry', 'appricot']) # extends one list with another
>>>fruit
['apple', 'pear', 'banana', 'cranberry', 'apricot']
>>>fruit.pop()
'apricot'
>>>fruit
['apple', 'pear', 'banana', 'cranberry']
>>>fruit.insert(0, 'apricot')
['apple', 'pear', 'banana', 'cranberry', 'apricot']
>>>fruit.reverse() # reverses order - modifies list inplace
>>>fruit
['apple', 'pear', 'banana', 'cranberry', 'apricot']
>>>fruit.sort()
>>>fruit
['apple', 'apricot', 'banana', 'cranberry', 'pear']
Dictionaries consist of key/value pairs and are written with curly braces:
>>> d = {'stringkey': 'String value', 1: 2, ('tuple', 1): {'dict': 'as value'}}
>>> d
{'stringkey': 'String value', ('tuple', 1): {'dict': 'as value'}, 1: 2}
That's a dictionary with a string, a tuple and an integer as keys. Any hashable type can be used as a dictionary key, and keys should be immutable. (Values can be any Python object.)
The above snippet illustrates that the order of dictionary keys are not guaranteed. In order to access a dictionary in key order, retrieve the keys as a list using the dictionary's 'keys' method, and then use the list's 'sort' method to obtain a list in predictable order:
>>> l = d.keys() >>> l.sort()
Dictionaries are basic to Python. Any Python object can be queried via its '__dict__' dictionary:
>>> class A:
... def __init__(self, a=1, b=2):
... self.a=a
... self.b=b
...
>>> a = A()
>>> a.__dict__
{'a': 1, 'b': 2}
>>> A.__dict__
{'__module__': '__main__', '__doc__': None, '__init__': <function
__init__ at 0x40401bfc>}
Dictionaries are fundamental to Zope. Here are the keys of the root object (bound to the name app):
>>> app.__dict__.keys() ['__error_log__', 'standard_html_footer', '_objects', 'temp_folder', 'session_data_manager', '_standard_objects_have_been_added', 'standard_template.pt', 'index_html', 'error_log', '_product_meta_types', '__before_publishing_traverse__', 'acl_users', '__allow_groups__', 'Control_Panel', '__before_traverse__', 'standard_error_message', 'plone', 'browser_id_manager', 'standard_html_header']






