Introduction to Artificial Intelligence with Applications to Public Health

Lecture 2.5 – Programming In Python

Dr. Anthony G. Francis, Jr.

February 14, 2005

Programming in Python

Topics:

·       Programming Systems

·       Compilers, Interpreters and Scripting Language

·       Data values

·       Variables

·       Functions

·       Recursion

·       Loops

·       Input and output

·       Lists

·       Dictionaries

·       String Processing

Programming Systems

Simply, ways of specifying sets of instructions that the computer can understand — punched cards, wiring arrangements, loader switches, or modern systems — bits in files that are edited with the computers themselves.  At the most basic level a machine takes a set of instructions; a programming system provides a notation to express a human task in ways that can be reliably translated into machine instructions.

For example, to tell a human to say hello, you might say, “Say ‘hello’ to the nice man.” And indeed telling a computer to do that is not much more difficult, except you type the instructions in a text file, like so:

print “Hello, world.”

People speak and act in the physical world, and human language is geared towards asking other humans to do complicated actions in the world — “Please hold the door,” “Read Chapters 1-3”, and so on.  Computers act in a world of bits and files, so their languages are geared towards tasks in that world, like listing all the lines in a file.  In Python, the instructions to do this are still fairly simple and almost human-readable:

file = open("census.txt")

for line in file:

       print line

Asking the computer to do something more sophisticated, like pulling the third column out of a census listing and summing it up, is still fairly simple in Python, but as our needs get more complicated, the programs that satisfy those needs become more complex and less and less immediately intuitive.  When programs become more complicated, we need to not just write instructions for the computer, but also leave comments for ourselves so we can understand the program later:

# Read census file from the standard location

file = open("census.txt")

file.readline()        # Throw away the header line

sum = 0              # Start with a sum of zero

for line in file:

# Each line is split by tabs "\t"

fields = line.split("\t")

# dependents are in the 3rd column

dependents = fields[2]       # 0 is first column

# add 1 to count head of household

sum = sum + dependents + 1

 

# When we’re done adding up, print the totals

print sum

This simple program exercises 75% of the Python you need to understand virtually all of Python.  Let’s step back for a moment and look at computing, and then unpack the details of how this program works.

Compilers, Interpreters and Scripting Languages

Programming systems can be broken down into several varieties:  direct machine codes, a human-readable language like assembly, or high-level languages like C, Basic, APL or Python.  Machine codes are rarely used except for embedded devices.  Assembly language is very close to the machine — uses human-readable words to stand for machine instructions, plus certain mumbles to enable convenient shorthand or provide access operating system features. 

The next stage is compiled programs — like assembly, these take a notation and transform it into machine code (or perhaps to assembly for further mechanical translation) but the machine level has largely disappeared.  This includes languages which are very close to the machine, like FORTRAN and C, and languages which are farther away, such as COBOL and ALGOL.

Beyond this are interpreted programs — these include some form of runtime program mediating between the notation and the machine.  One of the earliest such systems is LISP, whereas others are Basic and Smalltalk. (Many interpreted languages also have compilers; so while Lisp has a reputation for being slow, compiled Lisp can be faster than C). 

Later systems began to blur these distinctions.  The C language contained small kernel compiler supported by many libraries — port the compiler, and you could port the whole language.  Bytecode interpreters took this further by compiling their languages down to bytecode — a language for a “virtual machine” which runs independently of the underlying platforms, like USCD Pascal or Java. 

As systems got more complicated the need for running many different programs in sequence became important. Early scripting languages were purely interpreted — advanced job-control language which scheduled the running of programs written in other languages.  Modern scripting languages strike a balance — they contain runtime engines and libraries written in C and Assembler, and compile their programs into bytecodes which run on top of these runtimes, but can be run in interpreted mode, and call out to arbitrary programs written in other languages.  Perl is the best-known example of this.

Python is one of this last breed — a modern object oriented scripting language, compiled on the fly to bytecodes executed on a runtime engine available for almost all modern computer systems.  For fast execution it provides a large library of numeric routines and an easy ability to run C.  Best of all, it is designed to be very easy to read and use.

Data Values

Numbers – 1, 1.0. 1253152251

Strings – 'a', 'Hello, World', 'This string has “quotes” in it', """This string

Spans multiple

Lines"""

Lists= [1, 2, 3]; [“this”, “is”, “a”, “list”]

Tuples = (1,2,3)

Dictionaries = {1: “a”, 2: “b”}

Objects: ‘this string has quotes’.split(‘ ‘)

 

 

Variables

This = 1

This,that, theOther = 1,2,3

 

Functions

def square (n): n*n

 

Recursion

def factorial(n): if n<1: 1 else: n*factorial(n-1)

 

Loops

For thing in range(1,10): print thing

 

Input and output

Print “Hello”

Print “hello”,

This = read()

File = open(“this”)

File.readline()

File.read()

 

Lists

 

Dictionaries

Word[value]

 

String Processing

“hello”[0:3]

 

Artificial Intelligence in Python

 

Resources

Class Texts

·        Dive Into Python: Chapters 1-3

Further Reading

Lutz, M. & Ascher, D. (2003). Learning Python. 2nd ed. O’Reilly.

Online

·        General Programming

·        Python Main Sites

·        Python Tutorials

·        Artificial Intelligence in Python