Spring Semester 2006


Lecture Notes 03/02: A Quick Introduction to Python (Part One).

We must find a standard way to write programs, but this is the first one:

# This is a comment.

print "Howdy"

raw_input("\n\nThat's it. Press Enter to quit.")
That's basically it for the first chapter.

Now the second chapter starts with a program like this:

# This is a comment.

print \
"""
+------------------------+
|  How do you like that? |
+------------------------+
"""
raw_input("\n\nThat's it. Press Enter to quit.")
Strings are discussed, together with their operators and we see programs like:
# This is a comment. 

print "one" * 3 + "two"
print
print "\\\n\"\'\twhat? almost done..."
raw_input("\nThank you.")
Lots of small (sometimes important) features crop up:
# This is a comment. 

print "one",
print "one",
print "two"
print "two"

raw_input("***(go ahead. make my day)***");
Working with numbers requires careful thinking:
# This is a comment. 

print 2 * 3 / 4 # this is NOT the same as 2 * (3 / 4) 
print 3 / 4 * 2 # this is the same as 2 * (3 / 4), see? 
raw_input("\n\nAssociativity rocks! Press Enter to quit."); 
We then talked about variables:
# This is a comment. 

print "What's your name? ",
name = raw_input();

age = raw_input("How old are you? ")

print "So " + name + " you are " + age + " years old."

raw_input("Press Enter to quit."); 
Strings are objects, and they know a few things:
# What strings can do for you. 

string = "This is a string"

print string
print string.upper()
print string.lower()
print string.swapcase()
print string.replace('i', 'a')

raw_input("When done press Enter...")
We need to acknowledge differences between the various types by using conversion mechanisms:
# Let's add two numbers

one = raw_input("First number: ")

two = raw_input("Second number: ")

print one + " + " + two + " = " + str(int(one) + int(two))

raw_input("Press Enter to quit."); 
And that brings us on page 54.

Chapter 3 starts with with a game:

# Guess my number.

import random 

num = random.randrange(100) + 1

print "The secret number is " + str(num)

tries = 0

while True:
  guess = int(raw_input("What is the secret number? (" + str(num) + ") "))
  if guess > num: 
    print str(tries+1) + ": Try lower."
  elif guess < num: 
    print str(tries+1) + ": Try higher."
  else: 
    print "You guessed it! In " + str(tries + 1) + " attempts."
    break
  tries += 1
  if tries >= 5: # number of tries allowed 
    print "Sorry, you lost."
    tries = 0
    num = random.randrange(100) + 1
    
raw_input("Press Enter if you liked the game.")
And this, actually, in a nutshell is the entire chapter 3.

We can implement the same with for loops like in Chapter 4, which focuses on sequential data structures.

Chapter 4 starts small:

# chars in a string

name = raw_input("Type your name please: ")

print "That spells",

for char in name: 
  print char + " ",  

raw_input("Satisfied?")
It then proceeds to look at ways to index strings:
# indexing strings

name = raw_input("What's your name: ")

size = len(name)

for i in range(0, size, 1): 
  print name[i]

for i in range(size-1, -1, -1):
  print name[i] + " ", 

raw_input("How do you like that?")
There are a few specific features you need to review, such as:
# indexing strings

name = raw_input("What's your name: ")

size = len(name)

for i in range(1, size+1): 
  print name[-i] + " ", 

raw_input("How do you like that?")
Here's another typical example:
# the stenographer program

text = raw_input("Type something please: ")

result = ""

for letter in text:
  if letter.lower() not in "aeiou":
    result += letter

raw_input(result); 
Slicing is explained, then tuples (by comparison with strings):
# guess the scrambled word

import random

list = ("helicopter", "apple", "house")

for i in range(20):
  print random.choice(list)

word = random.choice(list)
print "We have chosen: " + word

for i in range(10):
  index = random.randrange(len(word))
  letter = word[index]
  print word[index] + " " + letter
  word = word[index+1:] + letter + word[:index]

print word

raw_input("what do you say?")
This really concludes chapter 4 and places us on page 128.

Chapter 5 starts with lists:

# sort a list of numbers in ascending order

numbers = [4, 5, 2, 9, 3, 6, 1]

print numbers

sorted = False

while not sorted: 
  sorted = True
  for index in range(len(numbers)-1): 
    if numbers[index] > numbers[index+1]: 
      temp = numbers[index]
      numbers[index] = numbers[index+1]
      numbers[index+1] = temp
      sorted = False

print numbers

raw_input("How do you like this?")
We just implemented what sort() already does for us, and even better.

A few other methods are discussed: append(), remove(), reverse(), etc. (see page 138).

The discussion then moves to nested structures (tuples or lists) and shared references.

Finally, dictionaries are introduced.

For the next few programs a Unix environment will be used:

sluggo%pwd
/.automount/grouchy/root/san/r1a0l7/www/classes/a202-dger/spr2006/pc
sluggo%which python
/usr/bin/python
sluggo%pico one.py
sluggo%cat one.py
#!/usr/bin/python

print "Howdy"
sluggo%ls -ld one*
-rw-r--r--  1 dgerman faculty 33 Mar  2 10:37 one.py
sluggo%chmod 700 one*
sluggo%./one.py
Howdy
sluggo%
The extension doesn't even have to be there:
sluggo%pico two
sluggo%ls -ld two
-rw-r--r--  1 dgerman faculty 73 Mar  2 10:39 two
sluggo%chmod 700 two
sluggo%cat two
#!/usr/bin/python

raw_input("Please press Enter to end the program.")


sluggo%./two
Please press Enter to end the program.<enter>
sluggo%
You can't see but I had to press Enter where marked with blue.

(I agree it looks a bit intimidating.)

Let's write a function which looks things up in a dictionary:

sluggo%cat two
#!/usr/bin/python

hash = { "dgerman" : "nairda", "lbird" : "dribl", "mjordan" : "abc" }

def search(key, dictionary):
  print "I am looking for " + key + " in the dictionary " + str(dictionary)
  print "The value associated with " + key + " is " + dictionary[key]

search("dgerman", hash)
search("lbird", hash)


sluggo%./two
I am looking for dgerman in the dictionary {'lbird': 'dribl', 'mjordan': 'abc', 'dgerman': 'nairda'}
The value associated with dgerman is nairda
I am looking for lbird in the dictionary {'lbird': 'dribl', 'mjordan': 'abc', 'dgerman': 'nairda'}
The value associated with lbird is dribl
sluggo%
We're now ready to write the Hangman game (chapter 5) and take a look at files.

sluggo%cat two
#!/usr/bin/python

# reading from plain text files

file = open("data.txt", "r")

contents = file.read()

print contents

file.close()

print "That was is, what do you think?"

sluggo%ls -ld data*
ls: No match.
sluggo%./two
Traceback (most recent call last):
  File "./two", line 5, in ?
    file = open("data.txt", "r")
IOError: [Errno 2] No such file or directory: 'data.txt'
sluggo%pico data.txt
sluggo%cat data.txt
this
is a test
a file
with four lines of text
sluggo%./two
this
is a test
a file
with four lines of text

That was is, what do you think?
sluggo%
Sometimes it's meaningful to work with command-line arguments:
sluggo%pwd
/.automount/grouchy/root/san/r1a0l7/www/classes/a202-dger/spr2006/pc
sluggo%pico two
sluggo%./two one two three
./two
one
two
three
sluggo%./two
./two
sluggo%cat two
#!/usr/bin/python

# command line arguments

import sys

for str in sys.argv:
  print str
sluggo%
As you have seen the name of the program is always there.

So one can get access this way too:

sluggo%pico two
sluggo%./two alpha beta gamma
alpha
sluggo%cat two
#!/usr/bin/python

# command line arguments

import sys

print sys.argv[1]
sluggo%
You can also read all the lines in a file into a list:
sluggo%pico data.txt
sluggo%cat data.txt
1. this
2. is a test
3. a file
4. with four numbered lines of text
sluggo%cat two
#!/usr/bin/python

# command line arguments

import sys

file = open(sys.argv[1], "r") # name of file on the command line!
lines = file.readlines()
for index in range(len(lines)):
  print lines[-index-1],
file.close()
sluggo%./two data.txt
4. with four numbered lines of text
3. a file
2. is a test
1. this
sluggo%
We then learn how to write to a file, and write a simple copy program:
sluggo%ls -l
total 3
-rwx------  1 dgerman faculty 374 Mar  2 11:04 cp
-rw-r--r--  1 dgerman faculty  93 Mar  2 11:05 data.txt
-rwx------  1 dgerman faculty  33 Mar  2 10:37 one.py
sluggo%rm one.py
rm: remove regular file `one.py'? y
sluggo%cat cp
#!/usr/bin/python

# a simple copy program

import sys

infile = open(sys.argv[1], "r") # name of input file on the command line
outfile = open(sys.argv[2], "w") # name of target file on the command line
lines = infile.readlines()
for index in range(len(lines)):
  outfile.write(lines[index]) # print the lines one by one in the same order
infile.close()
outfile.close()
sluggo%./cp data.txt dataCopy.txt
sluggo%ls -l
total 3
-rwx------  1 dgerman faculty 374 Mar  2 11:04 cp
-rw-r--r--  1 dgerman faculty  93 Mar  2 11:05 dataCopy.txt
-rw-r--r--  1 dgerman faculty  93 Mar  2 11:05 data.txt
sluggo%more data*
::::::::::::::
dataCopy.txt
::::::::::::::
this is a short
text file with a
few lines in it to
demonstrate copying files

that's it.

::::::::::::::
data.txt
::::::::::::::
this is a short
text file with a
few lines in it to
demonstrate copying files

that's it.

sluggo%
sluggo%
There are a few other topics related to file I/O, let's finish with the Hangman game though:
# I am writing a comment

word = "conspicuous"

# random word from a file of words

file = open("words", "r")
words = file.readlines()
file.close()

import random

word = words[random.randrange(len(words))].strip() # why?

print "Please guess the word " + word

missed = 0
guesses = ""
show = "-" * len(word)

while missed < 6: 
  letter = raw_input("(" + str(6-missed) + ") Guess a letter: ")
  print "You have guessed the letter " + letter
  result = ""
  for i in range(len(word)):  
    if word[i] == letter: 
      result += letter
    else: 
      result += show[i] 
  show = result     
  print show 
  if show == word: 
    print "Congratulations, you have won."
    print "You had " + str(missed) + " misses."
    break
  elif letter not in word: 
    missed += 1

if missed >= 6:
  print "Sorry, the word was: " + word
  print "You lost."  
raw_input("Done")
This last part was again written on Windows, and the file (words) contained three words, one word per line.

Here's how it works when you play with it:

Please guess the word apple
(6) Guess a letter: o
You have guessed the letter o
-----
(5) Guess a letter: e
You have guessed the letter e
----e
(5) Guess a letter: a
You have guessed the letter a
a---e
(5) Guess a letter: l
You have guessed the letter l
a--le
(5) Guess a letter: m
You have guessed the letter m
a--le
(4) Guess a letter: b
You have guessed the letter b
a--le
(3) Guess a letter: p
You have guessed the letter p
apple
Congratulations, you have won.
You had 3 misses.
Done


Last updated on Mar 1, 2006, by Adrian German for A202/A598 and I211