Python 101 - Introduction to Python - Part 1

by Dave Kuhlman
Wednesday, 3rd August 2005

Python is a high-level general purpose programming language. Because code is automatically compiled to byte code and executed, Python is suitable for use as a scripting language, Web application implementation language, etc. Because Python can be extended in C and C++, Python can provide the speed needed for even compute intensive tasks.

Important Features of Python 

Some things you will need to know:  

in Python would be:

if x:
    if y:
        f1()
    f2()

And, the convention is to use four spaces (and no tabs) for each level of indentation.

Where to go for Additional Help? 

Interactive Python

If you execute Python from the command line with no script, Python gives you an interactive prompt. This is an excellent facility for learning Python and for trying small snippets of code. Many of the examples that follow were developed using the Python interactive prompt.

In addition, there are tools that will give you a more powerful and fancy Python interactive mode. One example is IPython, which is available at http://ipython.scipy.org/. You may also want to consider using IDLE. IDLE is a graphical integrated development environment for Python; it contains a Python shell. You will find a script to start up IDLE in the Tools/scripts directory of your Python distribution. IDLE requires Tkinter.

Strings

What

In Python, strings are immutable sequences of characters. They are immutable in that in order to modify a string, you must produce a new string.

When

Any text information.

How

Create a new string from a constant:

s1 = 'abce'
s2 = "xyz"
s3 = """A
multi-line
string.
"""

Use any of the string methods, for example:

>>> 'The happy cat ran home.'.upper()
'THE HAPPY CAT RAN HOME.'
>>> 'The happy cat ran home.'.find('cat')
10
>>> 'The happy cat ran home.'.find('kitten')
-1
>>> 'The happy cat ran home.'.replace('cat', 'dog')
'The happy dog ran home.'

Type "help(str)" or see http://www.python.org/doc/current/lib/string-methods.html for more information on string methods.

You can also use the equivalent functions from the string module. For example:

>>> import string
>>> s1 = 'The happy cat ran home.'
>>> string.find(s1, 'happy')
4

See http://www.python.org/doc/current/lib/module-string.htmlfor more information on the string module.

There is also a string formatting operator: "%".

>>> state = 'California'
>>> 'It never rains in sunny %s.' % state
'It never rains in sunny California.'

You can use any of the following formatting characters:  

Conversion Meaning Notes 
d Signed integer decimal.  
i Signed integer decimal.  
o Unsigned octal. (1)
u Unsigned decimal.  
x Unsigned hexidecimal (lowercase). (2)
X Unsigned hexidecimal (uppercase). (2)
e Floating point exponential format (lowercase).  
E Floating point exponential format (uppercase).  
f Floating point decimal format.  
F Floating point decimal format.  
g Same as "e" if exponent is greater than -4 or less than precision, "f" otherwise.  
G Same as "E" if exponent is greater than -4 or less than precision, "F" otherwise.  
c Single character (accepts integer or single character string).  
r String (converts any python object using repr()). (3)
s String (converts any python object using str()). (4)
% No argument is converted, results in a "%" character in the result.  

And these flags:  

Flag Meaning 
# The value conversion will use the ``alternate form'' (where defined below).
0 The conversion will be zero padded for numeric values.
- The converted value is left adjusted (overrides the "0" conversion if both are given).
  (a space) A blank should be left before a positive number (or empty string) produced by a signed conversion.
+ A sign character ("+" or "-") will precede the conversion (overrides a "space" flag).

See http://www.python.org/doc/current/lib/typesseq-strings.htmlfor more information on string formatting.

You can also write strings to a file and read them from a file. Here are some examples:  

Notes:  

A few additional comments about strings:  

Sequences

What

There are several types of sequences in Python. We've already discussed strings. In this section we will describe lists and tuples. See http://www.python.org/doc/current/lib/typesseq.html for a description of the other sequence types (e.g. buffers and xrange objects).

Lists are dynamic arrays. They are arrays in the sense that you can index items in a list (for example "mylist[3]") and you can select sub-ranges (for example "mylist[2:4]"). They are dynamic in the sense that you can add and remove items after the list is created.

Tuples are light-weight lists, but differ from lists in that they are immutable. That is, once a tuple has been created, you cannot modify it. You can, of course, modify any (modifiable) objects that the tuple refers to.

Capabilities of lists:  

Capabilities of lists and tuples:  

When 

How

To create a list use:  

>>> items = [111, 222, 333]
>>> items
[111, 222, 333]
 
To add an item to the end of a list, use:  
 
>>> items.append(444)
>>> items
[111, 222, 333, 444]
 
To insert an item into a list, use: 
 
>>> items.insert(0, -1)
>>> items
[-1, 111, 222, 333, 444]
 
You can also push items onto the right end of a list and pop items off the right end of a list with append and pop
 
>>> items.append(555)
>>> items
[-1, 111, 222, 333, 444, 555]
>>> items.pop()
555
>>> items
[-1, 111, 222, 333, 444]
 
And, you can iterate over the items in a list with the for statement: 
 
>>> for item in items:
... print 'item:', item
...
item: -1
item: 111
item: 222
item: 333
item: 444

Dictionaries

What

Associative arrays.

Capabilities:  

For help on dictionaries, type:  

>>> help dict

at Python's interactive prompt, or:  

$ pydoc help
 
at the command line.
 
 When  

How

Create a dictionary with:  

>>> lookup = {}
>>> lookup
{}
</div>
or:  
<div class="verbatim">>>> def fruitfunc():
... print "I'm a fruit."
>>> def vegetablefunc():
... print "I'm a vegetable."
>>>
>>> lookup = {'fruit': fruitfunc, 'vegetable': vegetablefunc}
>>> lookup
{'vegetable': <function vegetablefunc at 0x4028980c>,
'fruit': <function fruitfunc at 0x4028e614>}
>>> lookup['fruit']()
I'm a fruit.
>>> lookup['vegetable']()
I'm a vegetable. </div>
<div class="verbatim">or: 
 </div>
<div class="verbatim">>>> lookup = dict((('aa', 11), ('bb', 22), ('cc', 33)))
>>> lookup
{'aa': 11, 'cc': 33, 'bb': 22}
>>>
</div>
Test for the existence of a key with:  
<div class="verbatim">[code]>>> if lookup.has_key('fruit'):
... print 'contains key "fruit"'
...
contains key "fruit"
>>>
</div>
or:  
<div class="verbatim">>>> if 'fruit' in lookup:
... print 'contains key "fruit"'
...
contains key "fruit"
>>>

Access the value of a key as follows:  

>>> print lookup['fruit']
<function fruitfunc at 0x4028e614>
>>> </div>
<div class="verbatim">>>> for key in lookup:
... print 'key: %s' % key
... lookup[key]()
...
key: vegetable
I'm a vegetable.
key: fruit
I'm a fruit.
>>>
 
And, remember that you can sub-class dictionaries. Here are two versions of the same example. The keyword arguments in the second version require Python 2.3: 
 
#
# This example works with Python 2.2.
class MyDict_for_python_22(dict):
def __init__(self, **kw):
for key in kw.keys():
self[key] = kw[key]
def show(self):
print 'Showing example for Python 2.2 ...'
for key in self.keys():
print 'key: %s value: %s' % (key, self[key])

def test_for_python_22():
d = MyDict_for_python_22(one=11, two=22, three=33)
d.show()

test_for_python_22()

#
# This example works with Python 2.3.
# Keyword support, when subclassing dictionaries, seems to have
# been enhanced in Python 2.3.
class MyDict(dict):
def show(self):
print 'Showing example for Python 2.3 ...'
for key in self.keys():
print 'key: %s value: %s' % (key, self[key])

def test():
d = MyDict(one=11, two=22, three=33)
d.show()

test()
 
Download as text (original file name: Examples/python_101_dict_example_1.py).

Running this example produces:  

Showing example for Python 2.2 ...
key: one value: 11
key: three value: 33
key: two value: 22
Showing example for Python 2.3 ...
key: three value: 33
key: two value: 22
key: one value: 11
A few comments about this example:  

Continue reading Part 2 of Python 101 - Introduction to Python.


Dave Kuhlman has worked for many years on a variety of software development projects, in several programming languages, and on more than one platform. Because of Python's clear syntax, developer friendliness, and broad utility, Dave focuses his energy on the Python language, on systems built with Python, and on developing documentation and training materials for those systems. Dave's current work involves XML processing in Python as well as the development of tools and documentation for Zope and the CMSs (content management systems) that run on top of Zope, Dave's current platform is Debian GNU/Linux; he has installed and administers a small network composed of several Linux boxes behind a Linux router/gateway. More information about Dave's work can be found at http://www.rexx.com/~dkuhlman.
View the original article Python 101 - Introduction to Python - Part 1