Python 101 - Introduction to Python - Part 2

by Dave Kuhlman
Wednesday, 3rd August 2005

Simple Statements

print

The print statement sends output to stdout.

Here are a few examples:  

print obj
print obj1, obj2, obj3
print "My name is %s" % name

Notes:

 

More information on the print statement is at http://www.python.org/doc/current/ref/print.html.

Note: Note to Jython users - Jython does not appear to support the file constructor for files. In the above example, replace file with open.

import

The import statement makes a module and its contents available for use.

Here are several forms of the import statement:

 

import test
Import module test. Refer to x in test with "test.x".

 

from test import x
Import x from test. Refer to x in test with "x".

 

from test import *
Import all objects from test. Refer to x in test with "x".

 

import test as theTest
Import test; make it available as theTest. Refer to object x with "theTest.x".

 

A few comments about import:

 

More information on import at http://www.python.org/doc/current/ref/import.html.

assert

Use the assert statement to place error checking statements in you code. Here is an example:

 

def test(arg1, arg2):
arg1 = float(arg1)
arg2 = float(arg2)
assert arg2 != 0, 'Bad dividend -- arg1: %f arg2: %f' % (arg1, arg2)
ratio = arg1 / arg2
print 'ratio:', ratio

When arg2 is zero, running this code will produce something like the following:

 

Traceback (most recent call last):
File "tmp.py", line 22, in ?
main()
File "tmp.py", line 18, in main
test(args[0], args[1])
File "tmp.py", line 8, in test
assert arg2 != 0, 'Bad dividend -- arg1: %f arg2: %f' % (arg1, arg2)
AssertionError: Bad dividend -- arg1: 2.000000 arg2: 0.000000

A few comments:

 

global

The problem -- Imagine a global variable NAME. If, in a function, the first mention of that variable is "name = NAME", then I'll get the value of the the global variable NAME. But, if, in a function, my first mention of that variable is an assignment to that variable, then I will create a new local variable, and will not refer to the global variable at all. Consider:

 

NAME = "Peach"

def show_global():
name = NAME
print '(show_global) name: %s' % name

def set_global():
NAME = 'Nectarine'
name = NAME
print '(set_global) name: %s' % name

show_global()
set_global()
show_global()

Running this code produces:

 

(show_global) name: Peach
(set_global) name: Nectarine
(show_global) name: Peach

The set_global modifies a local variable and not the global variable as I might have intended.

The solution -- How can I fix that? Here is how:

 

NAME = "Peach"

def show_global():
name = NAME
print '(show_global) name: %s' % name

def set_global():
global NAME
NAME = 'Nectarine'
name = NAME
print '(set_global) name: %s' % name

show_global()
set_global()
show_global()

Notice the global statement in function set_global. Running this code does modify the global variable NAME, and produces the following output:

 

(show_global) name: Peach
(set_global) name: Nectarine
(show_global) name: Nectarine

Comments:

 

Control Structures

if 

The if statement enables us to execute code (or not) depending on a condition.

 

Here is an example:

 

>>> y = 25
>>>
>>> if y > 15:
... print 'y is large'
... else:
... print 'y is small'
...
y is large
A few notes:

 

Here is an example:

 

>>> collection = [111,222,333]
>>> for item in collection:
... print 'item:', item
...
item: 111
item: 222
item: 333

Comments:

 

while

while is another repeating statement. It executes a block of code until a condition is false.

Here is an example:

 

>>> reply = 'repeat'
>>> while reply == 'repeat':
... print 'Hello'
... reply = raw_input('Enter "repeat" to do it again: ')
...
Hello
Enter "repeat" to do it again: repeat
Hello
Enter "repeat" to do it again: bye

Comments:

 

try-except and raise -- Exceptions

Use a try:except: block to catch an exception.

Use raise to raise an exception.

Comments and hints:

 

Reading Text Files

To read a text file, first create a file object. Here is an example:

 

inFile = file('messages.log', 'r')

Then use one or more of the file object's methods to process the contents of the file. Here are a few strategies:

 

Iterator objects

This section explains how to implement iterator objects, that is a class that obeys the iterator protocol.

We explain generators first -- A generator is a function which uses yield. Because it returns values with yield instead of with return, the function can be resumed immediately after the yield. Here is an example:

 

def generateItems(seq):
for item in seq:
yield 'item: %s' % item

anIter = generateItems([])
print 'dir(anIter):', dir(anIter)
anIter = generateItems([111,222,333])
for x in anIter:
print x
anIter = generateItems(['aaa', 'bbb', 'ccc'])
print anIter.next()
print anIter.next()
print anIter.next()
print anIter.next()

Running this example produces the following output:

 

dir(anIter): ['__class__', '__delattr__', '__doc__', '__getattribute__',
'__hash__', '__init__', '__iter__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__setattr__', '__str__', 'gi_frame',
'gi_running', 'next']
item: 111
item: 222
item: 333
item: aaa
item: bbb
item: ccc
Traceback (most recent call last):
File "iterator_generator.py", line 14, in ?
print anIter.next()
StopIteration

Notes:

 

Now, we will implement a class that obeys the iterator protocol. By doing so, we can produce "iterable" objects. Here is an example:

 

class IteratorExample:
def __init__(self, s):
self.s = s
self.next = self._next().next
self.exhausted = 0
def _next(self):
if not self.exhausted:
flag = 0
for x in self.s:
if flag:
flag = 0
yield x
else:
flag = 1
self.exhausted = 1
def __iter__(self):
return self._next()

def main():
a = IteratorExample('edcba')
for x in a:
print x
print '=' * 30
a = IteratorExample('abcde')
print a.next()
print a.next()
print a.next()
print a.next()
print a.next()
print a.next()

if __name__ == '__main__':
main()

Iterating over an instance of the above class produces every other object from the sequence with which the instance was constructed. Running the above example produces the following:

 

d
b
==============================
b
d
Traceback (most recent call last):
File "iterator_class.py", line 24, in ?
print a.next()
StopIteration

Explanation:

 

The definition of the iterator protocol is at http://www.python.org/doc/current/lib/typeiter.html.

Continue reading Part 3 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 2