Contents

  1. flow_example.py
  2. mystery.py
  3. oldmac.py
  4. scope.py
  5. wheeloffortune.wfiles_functions.py
  6. wheeloffortune.wfiles.py

flow_example.py 1/6

[
top][prev][next]
# Example of program flow
# Sara Sprenkle

def max(num1, num2):
	result = 0
	if num1 >= num2:
		result = num1
	else:
		result = num2
	return result

x = 12
y = eval(input("Enter a number: "))
z = max(x, y)
print("The max is", z)

mystery.py 2/6

[
top][prev][next]
# Mystery Program
# Used to demonstrate variable lifetimes and scope

def main():
    x = 10
    sum = sumEvens( x )
    print "The sum of even #s up to", x, "is", sum

def sumEvens(limit):
    total = 0
    for x in xrange(0, limit, 2):
        total += x	
    return total

main()


oldmac.py 3/6

[
top][prev][next]
# Print out verses of the song Old MacDonald
# Sara Sprenkle

BEGIN_END = "Old McDonald had a farm"
EIEIO = ", E-I-E-I-O"

def main():
    # call the verse function to print out a verse
    printVerse("dog", "ruff")
    printVerse("duck", "quack")
    
    animal_type = "cow"
    animal_sound = "moo"
    
    printVerse(animal_type, animal_sound)
    

# QUESTION: What happens if main called function as
# printVerse("ruff", "dog")

# prints a verse of Old MacDonald, plugging in the animal and sound
# parameters (which are strings), as appropriate.
def printVerse(animal, sound):
    print BEGIN_END + EIEIO
    print "And on that farm he had a " + animal + EIEIO
    print "With a " + sound + ", " + sound + " here"
    print "And a " + sound + ", " + sound + " there"
    print "Here a", sound
    print "There a", sound
    print "Everywhere a " + sound + ", " + sound
    print BEGIN_END + EIEIO
    print

main()


scope.py 4/6

[
top][prev][next]
# scope.py
# Program illustrating scope
# Note: NOT good coding style
# by Sara Sprenkle

def main():
    n = 30
    e = 0
    f = 2
    g = 3
    h = 4

    print("\nBefore the call to function1,")
    print("n = ", n)
    print("e = ", e)

    # QUESTION: How to change function1's call to execute other branch?
    i = function1(e, f, g, h)

    print("\nAfter the call to function1,")
    print("n = ", n)
    print("e = ", e)
    print("i = ", i)


def function1(a, b, c, d):
    # QUESTION: What would happen if the following line was commented
    # out?
    n = 400

    print("\nIn function1, ")
    print("n = ", n)
    print("a = ", a)

    if  a >= 1 :
        a += b+n;
        print("a = ", a, "after being modified")
        return a
    else :
        c += d+n
        return c

main()


wheeloffortune.wfiles_functions.py 5/6

[
top][prev][next]
# Wheel of Fortune
# By Sara Sprenkle

PROMPT="Enter a letter or try to solve the puzzle: "
TITLE_WIDTH=50
CATEGORY_NAMES = ["oscars", "grammy_noms", "famous_pairs"]

def printHeader():
    """Prints out the header for the game"""
    print("*"*TITLE_WIDTH)
    print("WHEEL".center(TITLE_WIDTH))
    print("OF".center(TITLE_WIDTH))
    print("FORTUNE!".center(TITLE_WIDTH))
    print("*"*TITLE_WIDTH )
    
def displayCategoryOptions():
    """
    Display the categories for the user to choose from
    """
    for num in range(len(CATEGORY_NAMES)):
        print("Press", (num+1), "for", CATEGORY_NAMES[num])

def createDisplayedPuzzle(puzzle):
    """
    Parameter:
        puzzle - a string for the user to guess
    Returns the puzzle to display, generated from the original puzzle.
    All the alphabetical characters are displayed as underscores.
    """
    displayedPuzzle = ""
    for char in puzzle:
        if char.isalpha():
            displayedPuzzle += "_"
        else:
            displayedPuzzle += char
    return displayedPuzzle


def handleGuess(guess, puzzle, displayedPuzzle):
    """
    Handles the user's guess appropriately, 
    including printing out information to user
    Parameters:
        guess - the user's guess (a string)
        puzzle - the puzzle to be guessed (a string)
        displayedPuzzle - the puzzle the user sees
    Returns the updated puzzle to display, based on the guessed letter
    """
    if len(guess) == 1 and guess.isalpha(): 
        numOccurences = puzzle.count(guess) + puzzle.count(guess.swapcase())
        if numOccurences > 0:
            print ("There are", numOccurences, guess + "'s", "in the phrase")
            # fill in puzzle
            updatedpuzzle=""
            for pos in range(len(puzzle)):
                if puzzle[pos] == guess or puzzle[pos] == guess.swapcase():
                    updatedpuzzle += puzzle[pos]
                else:
                    updatedpuzzle += displayedPuzzle[pos]
            displayedPuzzle = updatedpuzzle
            
            print ("\nThe puzzle is", displayedPuzzle)
        else:
            print ("Sorry, there are no", guess + "'s", "in the word")
    elif len(guess) != 1:
        # assumes that the user tried to solve the puzzle but got it wrong.
        print ("\tSorry, that is not correct.")
    else:
        print ("\tError: You must guess a letter.")
    
    print()  
    return displayedPuzzle
    
    
printHeader()

displayCategoryOptions()

# input from user about which puzzle file to use
selection = eval(input("Which category do you choose? "))
        
# open appropriate puzzle file based on the category name
puzzleFile = open("data/" + CATEGORY_NAMES[selection-1] + ".txt", "r")

puzzleid = 0

# each line in the puzzleFile is a puzzle
# go through them all ...
for puzzle in puzzleFile: 
    puzzle = puzzle.strip()
    
    puzzleid+=1

    # Display the current puzzle.  
    # All the alphabetical characters are displayed as underscores.
    displayedPuzzle = createDisplayedPuzzle(puzzle)
    print("Puzzle %d: %s" % (puzzleid, displayedPuzzle))
    print()
    
    # how many guesses it took to get it right
    numGuesses = 1
    
    guess = input(PROMPT)
    
    while guess.lower() != puzzle.lower() :
        displayedPuzzle = handleGuess(guess, puzzle, displayedPuzzle)
        guess = input(PROMPT)
        numGuesses += 1
            
    print ("Congratulations!  You solved the puzzle in", numGuesses, "guesses")

puzzleFile.close()

print("We're out of puzzles!  Thanks for playing!")

wheeloffortune.wfiles.py 6/6

[
top][prev][next]
# Wheel of Fortune
# By Sara Sprenkle

PROMPT="Enter a letter or try to solve the puzzle: "
TITLE_WIDTH=50

# print out a nice header
print("*"*TITLE_WIDTH)
print("WHEEL".center(TITLE_WIDTH))
print("OF".center(TITLE_WIDTH))
print("FORTUNE!".center(TITLE_WIDTH))
print("*"*TITLE_WIDTH )

categoryNames = ["oscars", "grammy_noms", "famous_pairs"]

for num in range(len(categoryNames)):
    print("Press", (num+1), "for", categoryNames[num])
    
# input from user about which puzzle file to use
selection = eval(input("Which category do you choose? "))
        
# change categoryName to file names
puzzleFile = open("data/" + categoryNames[selection-1] + ".txt", "r")

puzzleid = 0

# each line in the puzzleFile is a puzzle
# go through them all ...
for puzzle in puzzleFile: 
    puzzle = puzzle.strip()
    
    puzzleid+=1

    # Display the current puzzle.  
    # All the alphabetical characters are displayed as underscores.
    displayedPuzzle = ""
    for char in puzzle:
        if char.isalpha():
            displayedPuzzle += "_"
        else:
            displayedPuzzle += char

    print("Puzzle %d: %s" % (puzzleid, displayedPuzzle))
    print()
    
    # how many guesses it took to get it right
    numGuesses = 1
    
    guess = input(PROMPT)
    
    while guess.lower() != puzzle.lower() :
        if len(guess) == 1 and guess.isalpha(): 
            numOccurences = puzzle.count(guess) + puzzle.count(guess.swapcase())
            if numOccurences > 0:
                print ("There are", numOccurences, guess + "'s", "in the phrase")
                # fill in puzzle
                updatedpuzzle=""
                for pos in range(len(puzzle)):
                    if puzzle[pos] == guess or puzzle[pos] == guess.swapcase():
                        updatedpuzzle += puzzle[pos]
                    else:
                        updatedpuzzle += displayedPuzzle[pos]
                displayedPuzzle = updatedpuzzle
                
                print ("\nThe puzzle is", displayedPuzzle)
            else:
                print ("Sorry, there are no", guess + "'s", "in the word")
        elif len(guess) != 1:
            # assumes that the user tried to solve the puzzle but got it wrong.
            print ("\tSorry, that is not correct.")
        else:
            print ("\tError: You must guess a letter.")
        
        print()
        guess = input(PROMPT)
        numGuesses += 1
            
    print ("Congratulations!  You solved the puzzle in", numGuesses, "guesses")

puzzleFile.close()

print("We're out of puzzles!  Thanks for playing!")

Generated by GNU enscript 1.6.4.