CSC207 Software Design
Lectures
Introducing Python

Agile Languages

Fundamental tradeoff between:

How quickly correct code can be written

How quickly that code executes

People are expensive

Makes sense to write:

Time-critical libraries at a low level for speed

Everything else at the highest possible level

Python

Like the Unix shell, only better

(Much) more readable than Perl

Object-oriented (but in a gentle way)

Easy to integrate with C, Fortran, Java

Slower than C (but often as fast as Java)

But remember: things that make small programs easy to write can make large ones hard to maintain

A Python Program

# Run with "python helloworld.py"

# Assign a string to a variable.
# Note: no 'main()', no declarations
str = "Hello"

# Print strings (plus newline).
print str, "world!"

Running Python

Interactively (good for debugging)

By putting code in file, and loading it

$ python myfile.py

By making a native executable

Unix: #!/usr/local/bin/python

Windows: File association

By compiling to a self-contained program

Instructions are still actually interpreted

Interactive Use

$ python
>>> 3+5
8
>>> x = 3 * 7 ** 2
>>> print x
147
>>> x = "some" + "thing"
>>> print x
something

Variables

Variables are just names for values

Created by use

No declarations

Variables don't have types, but values do

x = 123                # integer
y = "one two three"    # string
z = x + y
TypeError: unsupported operand types for +

Must Define Before Use

Must give a variable a value before using it

Python doesn't try to guess a sensible value

# This is the whole program
print y
NameError: name 'y' is not defined

See how to handle errors later

Quoting Strings

Use either single or double quotes

Must be consistent

print 'a', "b", '"c"', "'d'"
a b "c" 'd'

Back-quoting converts value to string

print "carbon-" + 14
TypeError
print "carbon-" + `14`
carbon-14

Numbers and Arithmetic

The usual numeric types

14 is an integer (32-bit on most machines)

14.0 is floating point (64-bit)

1+4j is complex (2 x 64-bit)

Python borrows C's numeric operators

Including in-place forms

x  = 5 * 4 + 3    # x now 23
x -= 10           # x now 13
y  = x % 3        # remainder is 1

Booleans

True and False are true and false (d'oh)

Empty string, 0, and None are false

(Almost) everything else is true

Usual Boolean operators (and, or, not)

Short-circuit

Return the last thing evaluated, rather than 1 or 0

"a" or "b"
"a"
0 or "a"
"a"
"a" and "b"
"b"
"a" and 0 and (1/0)
0

Comparisons

Python borrows C's comparisons

Results are always 1 (true) or 0 (false)

= is assignment, == is equality

Assignment is a statement, not an expression

Comparisons can be chained together, as in mathematics

Strings are compared in dictionary order

print 3 < 5, 2.1 >= 2.2, "a" < "A", "Abc" < "AB"
1 0 0 0
print -1 < 0 < 1
1

String Operators

Use + for concatention, * for multiplication

greet = "Hi " + "there"
Hi there
jolly = "ho" * 3
hohoho

Conditionals

if, elif, and else

Use colon and indentation to show nesting

a = 3
if a < 0:
    print "less"
elif a == 0:
    print "equal"
else:
    print "greater"
greater

Why Indentation?

Based on studies from 1980s

It's what everyone looks at anyway

Just count the number of warnings in C/Java books about misleading indentation

While Loops

Use colon and indentation to show nesting

a = 3
while a > 0:
    print a
    a -= 1
3
2
1

Files

Use built-in function open() to open a file

First argument is path

Second is "r" (for read) or "w" for write

Result is a file object with methods for input and output

# Copy one file to another
input = open("file.txt", "r")    # open file.txt for reading
output = open("copy.txt", "w")   # open copy.txt for writing
line = input.readline()          # get first line
while line:                      # 'None' indicates end-of-file
    output.write(line)           # copy line to output
    line = input.readline()      # try for another line
input.close()                    # don't need file any longer
output.close()                   # we're done

Could also write this as:

input = open("file.txt", "r")
output = open("copy.txt", "w")
for line in input.xreadlines():
    output.write(line)
input.close()
output.close()

Or:

input = open("file.txt", "r")
contents = input.readlines()
input.close()
output = open("copy.txt", "w")
output.writelines(contents)
output.close()

$Id: pyintro.html,v 1.1.1.1 2004/01/04 05:02:31 reid Exp $