First Summer 2006


Lecture Notes Ten: Writing Meaningful Programs.
We start with this program:

scores = []
score = raw_input("Enter: ")
while score != 'done':
    scores.append(int(score))
    score = raw_input("Enter: ")
print scores

It collects numbers in a list (like in Chapter 5). Let's define a function (like in Chapter 6).

def average(scores):
    sum = 0
    for score in scores:
        sum += score
    return sum/float(len(scores))

scores = []
score = raw_input("Enter: ")
while score != 'done':
    scores.append(int(score))
    score = raw_input("Enter: ")
print scores
print average(scores)

We call it at the end and report the average.

If we called it after every line we'd get Problem Three in Homework Three:

def average(scores):
    sum = 0
    for score in scores:
        sum += score
    return sum/float(len(scores))

scores = []
score = raw_input("Enter: ")
while score != 'done':
    scores.append(int(score))
    print "Current average is: ", average(scores)
    score = raw_input("Enter: ")
print "Thank you for using this program."

Another program we'd like to discuss would be the word jumble:

import random
WORDS = ("apple", "house", "watermelon")
for i in range(10):
    word = random.choice(WORDS)
    print str(i) + ". " +word

As you can see random selection from a list (or tuple in this case) is straightforward.

The basic structure of the guess-my-number game applies here too:

import random
WORDS = ("apple", "house", "watermelon")
word = random.choice(WORDS)
print "I have selected " + word
guess = raw_input("What is the word: ")
while guess != word:
    guess = raw_input("Nope, please try again: ")
print "Great, you have guessed the word. "

Let's set up a function for the shuffling of the letters in the word:

def shuffle(word):
    jumble = ""
    while word:
        i = random.randrange(len(word))
        jumble = jumble + word[i]
        word = word[:i] + word[i+1:]
    return jumble
        
import random
WORDS = ("apple", "house", "watermelon")
word = random.choice(WORDS)
print "I have selected " + shuffle(word)
guess = raw_input("What is the word: ")
while guess != word:
    guess = raw_input("Nope, please try again: ")
print "Great, you have guessed the word. "

You see the expression in red above. A small mistake there yields infinite frustration. Be careful.

Lastly, we discuss reading from a file:

file = open("C:\Documents and Settings\Spring 2003\Desktop\data.txt", "r")

contents = file.read()

print contents

file.close()

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


Last updated: May 20, 2006 by Adrian German for A201/A597