Home > Lecture Notes > Python Resources > Python

[ Perl ] [ VBScript & Windows Script Host ] [ JavaScript ]

Introduction to Python


About This Guide

This is a brief introduction to the Python programming language under. The target audience is community college students taking their first-year "computer concepts" classes, most of whom have not taken an operating systems class or formal programming language class. My goal is to provide enough introductory background and information so that Python can be used as a vehicle for demonstrating broad conceptual topics such as languages in general; differences between low-level and high-level languages; compilers & interpreters; algorithms and basic control structures; and fundamental database concepts.

This guide is not intended to be a complete Python tutorial. The following links take you to the "official" Python Tutorial at www.python.org and to an introductory page with additional links for beginners:

[ TOP ]


The Python Language and Interpreter

Python is a general purpose, interpreted, high level programming language that also serves as a good scripting language. It was designed to be clean, easy to write, and easy to read. Several people have referred to it as "executable pseudo code". Python runs under many common environments including Windows, Macintosh, and the various flavors of Unix and Linux. Object Oriented Programming (OOP) is supported, (Python data types and the standard library are implemented as objects), but you are not forced to use only OO structures and syntax. Python is designed with a relatively simple core that gets its strength and power from a standard library of modules.

Python is frequently compared with Perl, and both are commonly called "scripting languages." While shell scripts were a common use for both languages in their early stages of development, Python and Perl are each full-featured programming languages in their current implementations. Each language, however, has its own distinct personality and "culture." One language's virtue is often considered the other language's fault. The above quotation about executable pseudo code is actually taken out of context; the second half says "...Perl is executable line noise."

Python programs are usually ASCII text files that are read, interpreted, compiled, and executed by the Python interpreter. However, programs can also be entered interactively directly into the interpreter, which is a convenient way to experiment with short code samples to see how various statements and expressions evaluate. Either method of executing a program requires that you download and install the Python interpreter, supporting libraries, and documentation on your computer.

The main source for Python is www.python.org.

Click on one of the Download links, or click on the link that contains the text "Python x.y.z (final)...", where x.y is the major and minor version number of the current stable release and z, if applicable, is the current patch level. The Windows installer will be named something like Python-x.y.z.exe , again where x.y.z are the current version number. (The 3rd part of the version number my not be present for the first version of a major release.)

As of Summer, 2003, the current version is 2.3. The Windows installer is about 9 Mb and requires about 30 - 36 Mb of disk space.

Installation is simply a matter of executing the installer and clicking "Next" for about 7 screens. At one point you will be shown a screen called "Select Components" with all the default components checked for installation. Accept the defaults unless you have a compelling reason to do otherwise. At the bottom of the "Select Components" screen is the "Advanced Options" button. Use this button to bring up a screen where you can choose to do a "Non-Admin Install" (Windows 2K/XP) and also choose whether or not to register file extensions. I personally choose not to register file extensions so that I can better control when my programs execute and what editor to use.

If you worry about installing software that never seems to go away, the Python Uninstall (from Control Panel::Add/Remove Programs) works very well. If you add any files to the installation path you will have to remove them yourself, however all the Python files and Registry keys will be removed by the un-installer.

[ TOP ]



Executing a Python Program

<Windows Console> <Command Path>

Python is a Console application. In the Windows environment you either start the Python interpreter in interactive mode with the python command from a Command Prompt, or via the Start menu: Programs::Python::Python 2.2. Using either method you will see the following:

Python 2.2.3 (#42, May 30 2003, 18:12:08) [MSC 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>

>>> is the Python interactive interpreter prompt.

There is also an Integraged DeveLopment Environment called IDLE that supports basic editing and file management. A good companion to this guide that used IDLE is:

The traditional "first program" since 1978 has been Hello World which is used to demonstrate trivial program start-up code and text output. In Python there is no start-up code (at least none that you are immediately aware of as a Python programmer), and the statement to display text is straight forward:

Python 2.2.3 (#42, May 30 2003, 18:12:08) [MSC 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print "Hello, World!"
Hello, World!
>>>

When you are finished entering program statements interactively, quit Python be entering the end of file character by holding down the Control key and pressing the Z key (Ctrl-Z), then hitting the Enter key.

>>> print "Hello, World!"
Hello, World!
>>> ^Z <Enter>

C:\>

As programs get longer it is inconvenient to enter each line of program code at the Python interpreter prompt, so programs are written in a text editor and saved as ASCII text files. Traditionally, Python programs use a .py extension.

Example:

# hello.py

print "Hello, World!"       # ubiquitous first program

 

D:\py_progs>python hello.py
Hello, World!

D:\py_progs>

[ TOP ]



Executing a Python Program

Windows Console <Command Path>

Use either of the following methods to open a Windows Console:

Command Prompt Shortcut RUN Command
  • Click on the Command Prompt menu item on the Windows Start Menu or one of its sub-menus.
    • By default a Command Prompt shortcut will be in the Accessories sub-menu tree:
      Start > Programs > Accessories
    • It may also be in the Start menu main opening menu
  • Open a Console window using the RUN command:  Start > Run
    • Windows 9x, ME
      Type command
    • Windows NT, 2000, XP
      Type cmd
    • Any Windows Operating System
      Type %COMSPEC%
  • Click OK

[ TOP ]



Executing a Python Program

<Windows Console> Command Path & PATH Variable

You can either enter the complete absolute path to your Python interpreter (which is what the shortcut on the Start Menu does), or you can set the system PATH variable for your Console session.

Example: (Absolute Path)

D:\py_progs>d:\python22\python hello.py
Hello, World!

D:\py_progs>

Example: (Setting PATH Variable)

D:\py_progs>path %PATH%;D:\Python22
D:\py_progs>python hello.py
Hello, World!

D:\py_progs>

[ TOP ]



Python Statements & Expressions

A Python program is a sequence of statements, which are typically composed of one or more expressions. Basic types of statements in most languages, Python included, are:

An expression is a piece of Python syntax in the form of a calculation that uses operators to combine values and variables, and evaluate them to some value. An expression can be used any place where a variable or literal value is used, pretty much like in mathematics. In Python an expression can also be a syntactically legal statement (it might not do anything, but it is legal).

Expressions entered in the Python interactive interpreter are evaluated immediately and their value displayed on the next line. The Python interpreter in interactive mode makes a pretty powerful desktop calculator:

Python 2.2.3 (#42, May 30 2003, 18:12:08) [MSC 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> 23
23
>>> 23 + 3 * 8
47
>>> (23 + 3) * 8
208
>>>

A statement is an instruction that Python can execute and tell the computer what to do, not unlike a statement in English: "Turn left on Main Street," "Close the door," etc. The structure of a Python is line-oriented; statements are terminated at the end of a line when you hit the Enter key and your text editor inserts the Carriage Return (ASCII 13) and LineFeed (ASCII 10) characters (on a Windows system). If you have a statement that is too long to fit on one line without scrolling off the right edge of the screen you can continue the statement to the next line by using a back-slash character (\) for the very last character of the line you want to continue. For line continuation the back-slash must be the very last character on the line without even a space following it, and it must be between keywords, variable names, operators, and quoted strings. Multiple statements separated by a semi- colon can be included on a single line.

The "#" character ('sharp', 'pound', 'hash') is the comment delimiter. Anything following this character to the end of the line is ignored by Python. There is no "multi-line" comment delimiter in Python.

# comments can be on their own line, or follow statements

cost = 12.5                     # simple statement assigns 12.5 to cost
price = cost * 0.2              # simple statement assigns value of
                                #   the expression cost * 0.2 to price

# multiple statements on one line separated by a semi-colon
cost = 12.5 ; price = cost * 0.2

# break up long statements and use indentation for clarity
total_credits = salesman_of_month_credit \
              + unused_vacation_credit \
              + senior_department_employee_credit

[ TOP ]



Python Data Types

Python is a dynamically typed language (as opposed to a statically typed language like C, C++, or Java). In plane language that means that you do not need to declare variables before you use them; variables spring into existence when you first use them.

Python is also strongly typed, meaning that once a variable is assigned a value, the value's data type stays bound to the variable for the life of the variable.

Python data types are as listed below:

[ TOP ]


Python Variables

Variables are used to store data items that can change (e.g. "vary") during the lifetime of a program. The data is actually stored in numbered memory addresses in the computer's Random Access Memory (RAM), however variables in high-level languages like Python provide convenient names for the memory addresses. Variables and memory addresses are similar to a house where you deliver the newspaper: it might have a lot number, plot number, section number, and township number for the official county engineer records; but you know it as "123 Main St.," "Mr. Smith's house," or maybe "the big red house on the corner with the mean dog."

Variables in Python do not have to be "declared" before they are used, they come into existence when you first use them. However, they must be initialized to some value before you can attempt to retrieve their value.

first_name = 'Fred'                 # variables created as we use them
last_name = 'Flintstone'

print last_name, mi, first_name     # NameError: name 'mi' is not defined

Python variable names are unlimited in length and are case sensitive. The variables total_price, Total_Price, and TOTAL_PRICE all refer to different locations in memory. Variable names can be made up of letters, digits, and the underscore character only (no spaces); must begin with a letter; and cannot be the same as a Python reserved word (such as for , while, etc.).

[ TOP ]



Python Operators

Assignment <Arithmetic> <Comparison> <Logical> <Bitwise> <Augmented>

As already seen in many of the examples = is the assignment operator. Assignment is left associative and multiple assignments can be made in one statement. Also, items in a sequence can be assigned to items in another sequence as long as each sequence has the same number of items. This is exploited in a Python idiom for swapping 2 variables. Finally, the expression on the right of the = evaluates before the assignment is made.

foo = 12
bar = 'a string'
x = y = z = 1.6         # z gets 1.6, then y gets z, then x gets y; all are 1.6
a, b, c = 3, 4, 5       # a = 3; b = 4; c = 5
(a, b, c) = (3, 4, 5)   # same thing, arguably clearer and easier to read

(a, b) = (b, a)         # swap a and b; a is now 4, b is now 3

a = a + b               # (a + b) is evaluated, then assigned to a

[ TOP ]


Python Operators

<Assignment> Arithmetic <Comparison> <Logical> <Bitwise> <Augmented>

Python uses many familiar or intuitive operators, such as +, -, *,and / for addition, subtraction, multiplication, and division. Division is a bit tricky, and changes are being implemented regarding default behavior for the / operator. Currently (including Python 2.3) if both operands are integers, the result will be integer division with the fractional part truncated (e.g. it does not round up).

>>> 7 / 3
2
>>> 7.0 / 3
2.3333333333333335
>>> 7 / 3.0
2.3333333333333335
>>>

Python 2.2 introduced an additional division operator, //, which explicitly performs integer division.

>>> 7 // 3
2
>>> 7.0 // 3
2.0
>>> 7 // 3.0
2.0
>>>

At some time in the future / will return true division, even if both operands are integers.

The exponentiation operator is **. An operator supported in virtually all programming languages that may be new is the modulus division operator. Modulus division returns the remainder rather than the quotient. In Python the modulus operator is %.

The + and * operators are overloaded for strings performing concatenation and repetition.

Operation           Operator    Example         Result

Addition                +           7 + 2            9
Subtraction             -           7 - 2            5
Multiplication          *           7 * 2            14
Division                /           7 / 2            3
Integer division        //          7 // 2           3
Exponentiation          **          7 ** 2           49
Modulus division        %           7 % 2            1
String concatenation    +           "Foo" + "Bar"    "FooBar"
String repetition       *           "Foo" * 3        "FooFooFoo"

Some notes regarding Python division:

[ TOP ]


Python Operators

<Assignment> <Arithmetic> Comparison <Logical> <Bitwise> <Augmented>

Comparisons are tested with the familiar < and > symbols used in mathematics for "less than" and "greater than". "Less than or equal to" and "greater than or equal to" use the <= and >= operators respectively. Equality is tested with the == operator and inequality ( "not equal to" ) is tested with the != operator. Note that = is used for assignment; == is used to test for equality.

NOTE: lhs = left hand side operand; rhs = right hand side operand

Comparison          Operator   Returns

Less than               <          True if lhs is less than rhs
Greater than            >          True if lhs is greater than rhs
Less than or equal      <=         True if lhs is not greater than rhs
Greater than or equal   >=         True if lhs is not less than rhs
Equal                   ==         True if lhs is equal to rhs
Not equal               !=         True if lhs is not equal to rhs

[ TOP ]


Python Operators

<Assignment> <Arithmetic> <Comparison> Logical <Bitwise> <Augmented>

The following truth tables for AND, OR, XOR, and NOT are helpful for understanding logical and bitwise operators. For logical operations think of 1 = TRUE and 0 = FALSE. XOR is exclusive OR; it means one OR the other, but not both

a   b     a AND b    a OR b     a XOR b    NOT b

0   0          0          0            0         1
0   1          0          1            1         0
1   0          0          1            1
1   1          1          1            0

Logical operators, also called Boolean operators, are used to evaluate logical expressions (e.g. TRUE or FALSE). They are commonly used to join comparison expressions to form complex comparison operations for conditional and iterative control flow statements.

NOTE: lhs = left hand side operand; rhs = right hand side operand

Logic               Operator    Returns

AND                     and         True only if lhs AND rhs are both true
OR                      or          True if lhs OR rhs is true, or both are true
NOT                     not         True if rhs is false; False if rhs is true

Logical operators normally combine 2 comparison expressions into one logical value, such as
    char == 'q' or char == 'Q'
(is the character a 'Q', either lower case OR upper case). Non computer examples:

[ TOP ]


Python Operators

<Assignment> <Arithmetic> <Comparison> <Logical> Bitwise <Augmented>

The bitwise operators use integer or long integer operands and view each operand as a string of bits.

NOTE: lhs = left hand side operand; rhs = right hand side operand

Operation          Operator   Returns

Bitwise AND             &        1 if lhs bit AND rhs bit = 1
Bitwise OR              |        1 if lhs bit OR rhs bit = 1
Bitwise Exclusive OR    ^        1 if lhs bit OR rhs bit = 1 AND lhs bit != rhs bit
Bitwise NOT             ~        1 if rhs bit = 0, 0 if rhs bit = 1
Bitwise Shift Right     >>       lhs bits shifted right rhs number of bits
Bitwise Shift Left      <<       lhs bits shifted left rhs number of bits
Bitwise shift operations discard any extra bits shifted off the left or right side and add 0's in the slots vacated by empty bits.
a = 97      # 61 hex, 01100001 binary
b = 98      # 62 hex, 01100010 binary

a & b       #  96 decimal, 60 hex, 01100000 binary
a | b       #  99 decimal, 63 hex, 01100011 binary
a ^ b       #   3 decimal, 03 hex, 00000011 binary
~a          # 158 decimal, 9E hex, 10011110 binary
a >> 2      #  24 decimal, 18 hex, 00011000 binary
b << 1      # 196 decimal, C4 hex, 11000100 binary

#   01100001     01100001     01100001   ~ 01100001       01100001          01100010
# & 01100010   | 01100010   ^ 01100010   ----------   >>2   01100001   <<1 01100010
# ----------   ----------   ----------     10011110   ------------      ------------
#   01100000     01100011     00000011                    00011000          11000100

[ TOP ]


Python Operators

<Assignment> <Arithmetic> <Comparison> <Logical> <Bitwise> Augmented

Augmented assignment combines the = assignment operator with a binary arithmetic or bitwise operator. Because it is common to write statements like
    total = total + price
you can write
    total += price

The augmented assignment operators are:
    
+=, -=, *=, /=, //=, %=, **=, |=, &=, ^=, >>=, <<=

[ TOP ]



Order of Operations (Precedence)

Python operators, like operators in math, follow rules of precedence, and the arithmetic-like operators behave as you would expect (exponents evaluate before multiplication & division, which evaluates before addition & subtraction, etc). With the exception of exponentiation ( **) all operations evaluate from left to right.

Default precedence can be overridden with the use of parentheses just like in mathematics: 3 + 4 * 5 = 23, however (3 + 4) * 5 = 35. It never hurts to use parentheses even when not strictly required if it helps clarify the meaning of the statement. If you do not want to keep a precedence chart handy a good rule is to simply remember that exponents evaluate before multiplication and division, which evaluates before addition and subtraction; for all other cases use parentheses. Anyone else who reads your code will be appreciative, and you will be also a week later when you read your code.

 
Order of Operation (Highest to Lowest)
(...), [...], {...} Tuple, list, dictionary creation
s[i], s[i:j]
f(...)
Index & slice operations
Function calls
+x, -x, ~x Unary operators
x**y Exponentiation (evaluates right to left)
x*y, x/y, x//y, x%y Multiplication, division, modulus (remainder) division
x+y, x-y Addition, subtraction
x<<y, x>>y Bit shift
x&y Bitwise and
x^y Bitwise exclusive or (xor)
x|y Bitwise or
x<y, x<=y, x>y, x>=y, x==y, x!=y
x is y, x is not y
x in y, x not in y
Comparison & equality
Identity
Membership
not x Logical negation
x and y Logical and
x or y Logical or

[ TOP ]



Python Input and Output

The standard output statement in Python is print with 0 or more arguments. By default print displays its argument on the Standard Output device (commonly called STDOUT), which is usually the monitor, and advances the cursor to the beginning of the next line. If you follow an argument with a comma print adds one space character and positions the cursor at the end of the same line. A print statement with no arguments simply displays a blank line. One or more comma delimited arguments displays the arguments separated by a single space.

Escape sequences (also called meta characters) can be embedded in strings to provide additional formatting and to display characters that would otherwise have special meaning. Common escape sequences are
    \n  new line
    \t  hard tab character
    \'  single quote character
    \"  double quote character
    \\  back-slash character

print 'Hello, World!'                       # single argument

name = 'Rockey'
print 'Hello', name                         # 2 arguments: Hello Rockey
print                                       # blank line

names = ['Rockey', 'Bullwinkle', 'Boris', 'Natasha']
print 'The', names[0], 'and', names[1], 'Show'
                                            # output:
                                            #   The Rockey and Bullwinkle Show

print "three\ntwo\none\nBlast Off!"         # three
                                            # two
                                            # one
                                            # Blast Off!
print "D:\\Python22\\python.exe"            # D:\Python22\python.exe

Two built-in functions, input() and raw_input(), get input from the Standard Input device (commonly called STDIN), which is usually the keyboard. input() is quite limited because it only reads numbers and will raise an exception if a user tries to input anything non-numeric. raw_input() is much more flexible since it reads all input as text. It is common to use raw_input() for all input then use the built-in functions int(), long(), or float() to convert the string to the desired number type.

input() and raw_input() take an optional argument: a text string to display as a prompt. The prompt string does not advance the cursor to the next line; use a newline escape if you want the use to enter input on the next line.

>>> name = raw_input("Enter your name: ")
Enter your name: Bullwinkle
>>> print 'Hello', name
Hello Bullwinkle
>>> num = raw_input("Enter a number: ")
Enter a number: 9
>>> print 'num =', num
num = 9
>>> type(num)
<type 'str'>
>>> num = int(num)
>>> type(num)
<type 'int'>
>>> print 2**num
512
>>>

[ TOP ]



Python Control Structures

<if> <while> <for> <def>

The main structure of a computer program is sequential: statements are executed in sequence until an instruction or statement changes the flow of control. Virtually all high-level programming languages support control constructs to determine the order in which instructions are executed:

Python Control Structures

if <while> <for> <def>

The if statement, with optional elif and else statements, allows a Python program to conditionally execute blocks of statements.

if <first_condition>:         # multi-branch conditional statement
    statement(s)
    ...
elif <second_condition>:
    statement(s)
    ...
elif < . . . >:              # additional elif's as needed
    ...
else:                        # the default if all else fails
    statement(s)
    ...

Note the spelling: elif is one word and "else" is not spelled out -- the 'se' is missing. Other languages have similar constructs with various combinations of spelling and word spacing.

Note also that there is no punctuation or keywords delimiting the boundaries of the conditional compound statement. Python determines the beginning of each compound statement from the keywords if, elif , and else followed by a conditional expression, followed by a colon. The body of each compound statement is determined by consistent indentation of each line in the block. The amount of space is not significant as long as it is the same for all lines in the block. You can use either spaces or hard tab characters, but should avoid using a mixture of both. 4 spaces is the most common, and most people configure their text editor to insert spaces when they press the tab key.

If you are still using Windows Notepad as your main text editor, writing Python programs might be your incentive to explore alternative editors. Notepad inserts a hard tab when you press the tab key, and the only tab width is 8 characters, which is usually too wide for most programs. See
     www.mhuffman.com/resource/ > Text Editors
for links to some suitable editors.

# if.py

order = raw_input("Total order: ")      # how much did customer spend?
order = float(order)                    # convert to floating point number

if order < 100:                         # check for first condition
    discount = order * .1

elif order < 500:                       # check for next condition
    discount = order * .15

else:                                   # easy to add additional test
    discount = order * .2               # big spender gets big discount

print "Your discount: $", discount      # display results

 

D:\py_progs>python if.py
What is your total order? 80
Your discount is $ 8.0

D:\py_progs>python if.py
What is your total order? 200
Your discount is $ 30.0

D:\py_progs>python if.py
What is your total order? 600
Your discount is $ 120.0

D:\py_progs>

The output is probably not quite formatted as you would like it. However, when first learning a language these details are best ignored. It is far more important to learn and understand the basic syntax and control of the program. When you are ready to explore string formatting look in the online documentation:
    Library Reference -> Sequence Types -> String Formatting Operations

OK, for a few format specifiers that cover a majority of situations see String Formatting below

Python does not have a "switch" or "select case" construct like some other languages for multi-way if ... elif branches, as handy as it would be at times.

[ TOP ]



Python Control Structures

<if> while; <for> <def>

The fundamental construct to iterate, or repeat a block of code more than once, is the while loop. Technically all loops can be written using while. However, additional looping structures are useful in a high-level language, especially if the number if iterations is known ahead of time. In those cases a for loop is usually a better choice.

while <condition>:
    statement(s)
    ...

while tests a condition at the beginning of the loop, executes the body of the loop if the test passes the specified condition, then goes back to the top and tests the condition again. As long as the test passes the condition the body of the loop continues to be executed.

Like the if compound statement, while statement blocks are delimited by the while keyword, the colon following the condition, and uniform indentation of the compound statement block.

# while.py

print 'Calculate powers of 2'
print                               # blank line for spacing

i = 0
while i < 8:
    print 2 ** i, '\t',             # trailing comma, no newline
    i += 1                          # be sure to include logic that
                                    #  will terminate the loop
                                    # augmented assignment; same as i = i + 1
print                               # send final newline

 

D:\py_progs>python while.py
Calculate powers of 2

1       2       4       8       16      32      64      128

D:\py_progs>

We can exit a loop before the end with the break statement and we can jump back to the top of the loop with the continue statement.

Here is an example where we do not know how add a series of numbers.

# sumloop.py
#   add numbers until user says no
#   demonstrate continue and break in while loop

sum = raw_input('Enter first number: ')         # first number to get started
sum = float(sum)                                # convert to floating point

while 1:                                        # infinite loop
    n = raw_input('Enter next number: ')        # get next number
    n = float(n)

    sum = sum + n                               # running sum of numbers
    print 'Sum =', sum                          #   display the sum
    choice = raw_input('Continue? (y/n)')       # add another number?

    if choice == 'y' or choice == 'Y':          # loop while 'y' or 'Y'
        continue
    elif choice == 'n' or choice == 'N':        # break out of loop
        break                                   #   if choice is 'n' or 'N'
    else:
        print 'Enter y or n'                    # remind user of proper response
                                        # a better design would be NOT to simply
                                        # go to top and ask for another number

 

D:\py_progs>python sumloop.py
Enter first number: 4.5
Enter next number: 3.3
Sum = 7.8
Continue? (y/n)y
Enter next number: 5
Sum = 12.8
Continue? (y/n)Y
Enter next number: 2.1
Sum = 14.9
Continue? (y/n)n

D:\py_progs>

We don't know how many numbers there will be, but there must be at least 2 since it makes no sense to add 1 number. After we get the first number we ask the user for the next number and add it to the sum.

while 1: sets up an infinite loop: the constant 1 will always be true. Next we prompt for the next number, add it to the sum, then ask the user if she wants to continue adding numbers. Then we make sure the user entered a proper response. We could just check to see if our user enter a 'y' or 'Y' and assume anything else meant no. However, if we were doing something critical, like verifying the user wanted to format a disk, it is a good plan to verify all cases. If the user hits a wrong key she will get a reminder of the possible choices and go back to the top of the loop. This is not the best design, and would probably irritate the user, but the idea was to show break and continue control the loop.

Note the use of the logical operator or join 2 simple conditional expressions into a complex expression to test for lower or upper case characters.

[ TOP ]



Python Control Structures

<if> <while> for <def>

The for loop iterates through each item in a sequence.

for variable in sequence:
    statement(s)
    ...

The following example prints the items in a list

# for1.py
# iterate over a sequence with for loop

name_list = ['Guido', 'Larry', 'Matz', 'Bjarne', 'Dennis']

for name in name_list:
    print name

 

D:\py_progs>python for1.py
Guido
Larry
Matz
Bjarne
Dennis

D:\py_progs>

The following while loop accomplishes the same thing, but must initialize a loop counter to 0, then increment the index each time in the loop. Forgetting either one of these critical details is a common mistake, especially in more complex loops where the loop variable gets lost in the logic of the bigger problem. Notice how the for loop version is simpler and more readable; it is effectively "self documenting."

index = 0
while index < len(name_list):
    print name_list[index]
    index += 1

When the number of iterations is known in advance, as in the while loop powers of 2 example above, it seems that a for loop would be better. And it is, but where is the sequence to iterate over? We could create a "throwaway list" that contained as many items as iterations we wanted to make:

for i in [0, 1, 2, 3, 4, 5, 6, 7]:      # temporary list of 8 items
    print 2 ** i, '\t',
print                                   # final newline

This works, but would not be as much fun for 100 iterations! Fortunately lists of consecutive numbers are common and Python provides the built-in range() function which takes 1, 2, or three arguments:
    range(n) returns a list of integers from 0 to n
    range(m, n) returns a list of integers from m to n
    range(m, n, s) returns a list of integers from m to n in steps of s

To create a list in descending order use the 3-argument version of range() where m is less than n and s is a negative number

>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(4, 10)
[4, 5, 6, 7, 8, 9]
>>> range(4, 10, 2)
[4, 6, 8]
>>> range(10, 0, -1)
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
>>>

We can now revise the powers of 2 while loop using a common Python idiom for looping a known number of times using the for loop and the range() function:

# for2.py

print 'Calculate powers of 2'
print                               # blank line for spacing

for i in range(8):                  # temporary list of 8 items
    print 2 ** i, '\t',             #   created by range()
print                               # final newline

Using the 2-argument version of range() is arguably more readable and self documenting:

for i in range(0, 8):               # temporary list of 8 items
    print 2 ** i, '\t',             #   created by range()
print                               # final newline

[ TOP ]



Python Control Structures

<if> <while> <for> def

Technically all algorithms can be implemented with 3 fundamental structures: sequence, selection, and looping. However, as programs grow beyond a few dozen lines, subprograms allow us to factor out blocks of statements that perform tasks we will use over and over in our program (and possibly other programs), test and debug the statements, give them a name, and then call them without worrying about the details. Examples seen already are the built- in range(), len(), raw_input(), and float() functions.

Python subprograms are functions and are defined using the def keyword followed by the name of the function, a pair of parentheses (possibly empty) containing a list of parameters, and a colon. Like the conditional and looping compound statements, function blocks are delimited by the def keyword, the line just described, and uniform indentation.

def func_name(param1, param2, ...):
    statement(s)
    ...
    return value            # optional

Some languages differentiate between subprograms that return values and subprograms that simply execute statements. In Python all subprograms are functions; if a function does not explicitly return a value, the function returns the special "null" data type called None

Lets take a rather trivial example of computing the area of a circle (A = π r2). Using Python in interactive mode we can knock out a quick solution:

>>> r = 4
>>> a = 3.14159 * r**2
>>> print 'area =', a
area = 50.26544
>>>

We might discover, however, that we need areas of more circles of various sizes, and we want to use our calculation in a bigger program. Rather than repeat the calculation each time we need it (and risk getting the value of Pi wrong) we can "factor" the repeated calculation out of our program into a function. By the way, another problem with the initial solution is the variable names r and a. While OK in a very small script (or in a small function), they are not very descriptive when sprinkled about in a larger program, and being very "generic" can easily get used for other values at some time not related to our radius and area.

Define a function to calculate the area of a circle and return the result. We are adding a layer of abstraction to our program. Once we know how to compute the area of a circle we wrap it up in a "black box" and use it without further thought of what is going on inside. Note that in Python functions must be defined at a point in the source code before they can be used.

# area1.py
# compute area of a circle

# function definitions must be defined before they are called
def area(r):
    a = 3.14159 * (r ** 2)      # calculate area
    return a                    # return result to caller

radius = float(raw_input("Radius: "))
print 'Area of circle with radius', radius, '=', area(radius)

 

D:\py_progs>python area1.py
Radius: 3.6
Area of circle with radius 3.6 = 40.7150064

D:\py_progs>

Variables declared within a function are local to the function; r and a are not visible outside the area() function. While not terribly descriptive in a broad context, there is little doubt what 'r' and 'a' refer to in a small area subprogram.

Python comes with an extensive standard library of modules and functions we can use in programs. The math module has many useful math related functions as well as a constant for Pi. To use the math module we have to import it into our program, then use the "dot notation" to refer to attributes of the imported module

# area2.py
# compute area of a circle
# import standard library math module and use pi attribute

import math

def area(r):
    a = math.pi * (r ** 2)      # calculate area
    return a                    # return result to caller

radius = float(raw_input("Radius: "))
print 'Area of circle with radius', radius, '=', area(radius)

print 'pi =', math.pi

The attributes of the math available to our program, and we can print out the value of Pi

D:\py_progs>python area2.py
Radius: 2.1
Area of circle with radius 2.1 = 13.8544236023
pi = 3.14159265359

D:\py_progs>

If we don't want to use the dot notation we can import specific attributes of a module using the from keyword:
    from math import pi

Unfortunately, we now have a global variable named pi in our program. The solution is to import math.pi in local scope inside the area() function so that pi is only visible within the function

def area(r):
    from math import pi

    a = pi * (r ** 2)           # calculate area
    return a                    # return result to caller

radius = float(raw_input("Radius: "))
print 'Area of circle with radius', radius, '=', area(radius)

print 'pi =', pi        # NameError: name 'pi' is not defined

The area() function works for normal input, but what if the user enters 0, or a negative number, or not a number at all? Some design considerations are whether to check for these errors at the point of user input, or in the subprogram. Python provides excellent support for error handling through the use of exceptions which are beyond the scope of this brief guide

[ TOP ]



String Formatting

Here are a few format specifiers that cover a majority of situations; refer to the Python documentation for the complete set. The syntax is:
    %[modifiers]format value
    %[mod]format ... %[mod]format %(value, value, ...)

All formats begin with the % character and must have at least a format specifier character. Common format specifier characters are s for a string, d for an unsigned integer in decimal notation, and f for a floating point number.

Between the % and the format specifier character you may add modifiers to indicate, among other things, field width, precision (for floating point numbers) and justification (right or left) within the field.

Common modifiers, in order (following the % and preceding the format specifier character) are:
    - to indicate left justification
    + to display the numeric sign( + or 0)
    0 to pad with leading zeros

Follow the above modifiers with a width and optional precision modifier in the form
    m.n
where m is the total width (including decimal point and numeric sign character and n is the precision. If you specify a width too narrow for the precision and or additional characters the precision will be honored and you will get a wider field. In other words, you will not loose information.

# format1.py

order = raw_input("Total order: ")          # how much did customer spend?
order = float(order)                        # convert to floating point number

if order < 100:                             # check for first condition
    discount = order * .1

elif order < 500:                           # check for next condition
    discount = order * .15

else:                                       # easy to add additional test
    discount = order * .2                   # big spender gets big discount

print "Your discount: $", discount          # display results

print "Your discount: $%6.2f" % discount    # no comma, no space following '$'
                                            # note total width is 6 characters
print "Your discount: $%8.2f" % discount    # total width is 8 characters
print "Your discount: $%4.2f" % discount    # requested width 4, no data lost

 

D:\py_progs>python format1.py
What is your total order? 600
Your discount is $ 120.0
Your discount is $120.00
Your discount is $  120.00
Your discount is $120.00

D:\py_progs>

String formats are handy when dealing with numbers of various sizes that you want to line up in columns

# format2.py

a = 3
b = 48
c = 1492
print "a:%6d\nb:%6d\nc:%6d" %(a, b, c)      # line up numbers

 

D:\py_progs>python format2.py
a:     3
b:    48
c:  1492

D:\py_progs>

String formats are particularly useful for generating database reports. Notice in this example that the format string has been saved to a string variable so we do not have to repeat it. Something else new here is a "list of lists." We have the names list, but instead of each item being a single string or number, the item is another list (of 4 strings). Notice also that we create an anonymous list in each .append call.

# format3.py

format = '%-15s%-15s%-20s%-20s'                             # format string

print format %('LName', 'FName', 'JobTitle', 'Home')
print format %('-----', '-----', '--------', '----')
print

names = []
names.append(['Badenov', 'Boris', 'Pottsylvania', 'No-Goodnik'])
names.append(['Squirrel', 'Rockey', 'Frostbite Falls', 'All-American Hero'])
names.append(['Moose', 'Bullwinkle', 'Frostbite Falls', 'Mr Know-It-All'])
names.append(['Do-Right', 'Dudley', 'Yukon Territory', 'Mountie'])

for name in names:
    print format %(name[0], name[1], name[3], name[2])

 

D:\py_progs>python format3.py
LName          FName          JobTitle            Home
-----          -----          --------            ----

Badenov        Boris          No-Goodnik          Pottsylvania
Squirrel       Rockey         All-American Hero   Frostbite Falls
Moose          Bullwinkle     Mr Know-It-All      Frostbite Falls
Do-Right       Dudley         Mountie             Yukon Territory

D:\py_progs>

[ TOP ]



Text & String Processing

Strings, like all data types in Python, are objects. Current versions of Python include the built-inb

Languages like Python tend to work with text most of the time; 90% is a common estimate. Python has very extensive support for strings via the built-in string object methods, built-in functions, and sequence operations such as indexing and slicing.

Here is an example showing the .strip() function to strip leading and trailing white space from a string and the slice operation to extract sub strings from a fixed-width data record (fields are specified by fixed column indexes). Look up "String Methods" (under "Sequence Types") in the Python Library Reference to see other string object methods.

# substr.py
#
# Demo sequence slices and string object methods
# ----------------------------------------------------------------------

#                   1         2         3         4         5         6
#         0123456789012345678901234567890123456789012345678901234567890

record = 'Rocky       Squirrel  1 Hero Way        Frostbite Falls  MN'

fname   = record[0:12].strip()          # strip white space from slice
lname   = record[12:22].strip()         # slice using start index and length
address = record[22:22+18].strip()      # length argument as an expression
city    = record[40:40+17].strip()

print "First Name:", fname
print "Last Name: ", lname
print "Address:   ", address
print "City/State:", city, record[-3:]

 

D:\py_progs>python substr.py
First Name: Rocky
Last Name:  Squirrel
Address:    1 Hero Way
City/State: Frostbite Falls  MN

D:\py_progs>

[ TOP ]



Where to Next?

Copy the trivial examples on this page (copy and paste directly from your browser or download the source code) into a text editor and get them to run on your own system. Better yet, type them in from scratch; you will be surprised how much more you learn by typing in source code as opposed to cutting and pasting. Sort of like rewriting your class notes... Then make some changes: modify the user prompts, test for different conditions, modify the loops (count down, count by 2's, 3's, etc.)

Design and write a 4-function calculator. Write an algorithm to prompt the user for 2 numbers and whether she wants to add, subtract, divide, or multiply. Write the program and test it. Add detection for an attempt to divide by zero. When that is working see if you can wrap the whole thing in a loop that lets the user do additional calculations until she wants to quit.

Explore the built-in string object attributes (or the string module if you have an older version of Python). Work with files and learn how to do file input and output.

Explore Regular Expressions (import re). Regular expressions have been an important feature of the Unix operating system utilities and scripting languages (shell scripts, Sed, AWK, Perl, etc) for years and are finally being incorporated in recent Microsoft technologies including Windows Script Host and .NET.
"Regular expressions are to strings what math is to numbers." (Andrew Clinick, Microsoft Script Technology Program Manager, 1999)

[ TOP ]



Where to Next?

Links & Resources <Books> <Thoughts>

[ TOP ]



Where to Next?

<Links> Books <Thoughts>

Recently Python has become a popular subject to write books about and new ones are coming out monthly. Two excellent sources for beginners and first-language programmers are

Both are available as free downloads from the respective authors' Web sites (see the links section above) and in dead tree versions. After working through a few of the many excellent on line tutorials the following 2 books should have good lasting value for further Python study. Neither is a "beginner's" guide, although Core Python Programming is more tutorial in nature than the Nutshell book

Core Python Programming
Wesley J. Chun
Prentice Hall PTR, 2000
ISBN: 0-1302-6036-3
Reviews:
www-106.ibm.com/developerworks/linux/library/l-pbook3.html
There are several Python book reviews on this page, scroll down to find this title.

www.linuxjournal.com/article.php?sid=4564
Python in a Nutshell
Alex Martelli
O'Reilly & Associates, 2003
ISBN: 0-5960-0188-6
More text and less "pure reference" than other O'Reilly <insert language> in a Nutshell books, but not a tutorial for beginners. Assumes a good working knowledge of another programming language and Object Oriented Programming.

Chapter 4, "The Python Language," (about 40 pages) is a good overview of the language and is available for download from O'Reilly:
www.oreilly.com/catalog/pythonian/chapter/ch04.pdf

Review:
www.unixreview.com/documents/s=7781/ur0303j/

[ TOP ]



Where to Next?

<Links> <Books> Final Thoughts

The only way to learn a programming language is to jump in and write code. Look at examples in books, articles, and online tutorials. Type them in a text editor and run them. Then look up what you don't understand in the Python documentation and try to figure out what is going on. Pretty soon you will be looking up less and understanding more. You can do it! Think of it as a different kind of cross-word puzzle, or a new game..

[ TOP ]



Example Source Code

All example Python programs in this guide begin with a comment identifying the name of a file available for download. All files are in the archive http://www.mhuffman.com/notes/language/src_py/py_examples.zip.

[ TOP ]



Copyright Notice

Introduction to Python Copyright © 2003 Michael B. Huffman

The author gives general permission to copy and distribute this document in any medium provided that all copies contain an acknowledgement of authorship and the URL of the original document:  http://www.mhuffman.com/notes/language/py_intro.htm

Mike Huffman: 

[ TOP ]


Valid HTML 4.01!