Contents

  1. average2.py
  2. average2_withmain.py
  3. flow_example.py
  4. mystery.py
  5. oldmac.py
  6. oldmac_with_forloop.py
  7. wheeloffortune.wfiles_functions.py
  8. wheeloffortune.wfiles.py

average2.py 1/8

[
top][prev][next]
# Program to find the average of two numbers
# by Sara Sprenkle

def average2(num1, num2):
    """
    Parameters: two numbers to be averaged
    Returns the average of two numbers
    """
    average = (num1 + num2)/2
    return average
    
print("This program will find the average of two numbers.")
print()

num1 = eval(input("Enter the first number: " ))
num2 = eval(input("Enter the second number: "))

# calculate the average of the two numbers
average = average2(num1, num2)

print("The average of", num1, "and", num2, "is", average)

average2_withmain.py 2/8

[
top][prev][next]
# Program to find the average of two numbers.
# Demonstrates using a main function.
# by Sara Sprenkle

def main():
    print("This program will find the average of two numbers.")
    print()
    
    num1 = eval(input("Enter the first number: " ))
    num2 = eval(input("Enter the second number: "))
    
    # calculate the average of the two numbers
    average = average2(num1, num2)
    
    print("The average of", num1, "and", num2, "is", average)

def average2(num1, num2):
    """
    Parameters: two numbers to be averaged
    Returns the average of two numbers
    """
    average = (num1 + num2)/2
    return average
    
main()


flow_example.py 3/8

[
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 = float(input("Enter a number: "))
z = max(x, y)
print("The max is", z)

mystery.py 4/8

[
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 range(0, limit, 2):
        total += x	
    return total

main()


oldmac.py 5/8

[
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()


oldmac_with_forloop.py 6/8

[
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():    
    animals=["dog", "duck", "cow", "pig"]
    sounds=["arf", "quack", "moo", "oink"]

    for i in range(len(animals)):
        animal_type = animals[i]
        animal_sound = sounds[i]
        
        printVerse(animal_type, animal_sound)
    

def printVerse(animal, sound):
    """
    prints a verse of Old MacDonald, plugging in the animal and sound
    parameters (which are strings), as appropriate.
    """
    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()

# Used to prevent automatically executing the main function when the 
# program/module is imported.
if __name__ == '__main__':
    main()
#main()

wheeloffortune.wfiles_functions.py 7/8

[
top][prev][next]
# Wheel of Fortune - refactored to use functions.
# Consider the readability of the "main" chunk of 
# code when we have functions.
# By Sara Sprenkle

PROMPT="Enter a letter or try to solve the puzzle: "
TITLE_WIDTH=50
CATEGORY_NAMES = ["whatareyoudoing", "beforeandafter", "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, possibleGuesses):
    """
    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")
        removeGuess(possibleGuesses, guess)
    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
    
def initializePossibleGuesses():
    myPossibleGuesses = []
    for x in range(97, 123):
        myPossibleGuesses.append(chr(x))
    return myPossibleGuesses

def removeGuess(guesses, guess):
    if guess.lower() in guesses:
        guesses.remove(guess.lower())
        
def displayPossibleGuesses(myPossGuesses):
    print("Letters not yet chosen: ", end="")
    for letter in myPossGuesses:
        print(letter, end=" ")
    print("\n")
    
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
    
    possibleGuesses = initializePossibleGuesses()
    
    guess = input(PROMPT)
    
    while guess.lower() != puzzle.lower() :
        displayedPuzzle = handleGuess(guess, puzzle, displayedPuzzle, possibleGuesses)
        displayPossibleGuesses(possibleGuesses)
        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 8/8

[
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 = ["whatareyoudoing", "beforeandafter", "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
    
    possibleGuesses = []
    for x in range(97, 123):
        possibleGuesses.append(chr(x))
    
    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")
                
            # update the possible guesses 
            if guess.lower() in possibleGuesses:
                possibleGuesses.remove(guess.lower())
        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()
        print("Letters not yet chosen: ", end="")
        for letter in possibleGuesses:
            print(letter, end=" ")
        print("\n")
        
        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.6.