Contents
- average2.py
- average2_withmain.py
- binaryToDecimal.test.py
- flow_example.py
- mystery.py
- oldmac.py
- oldmac_with_forloop.py
- wheeloffortune.wfiles_functions.py
- wheeloffortune.wfiles.py
average2.py 1/9
[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/9
[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()
binaryToDecimal.test.py 3/9
[top][prev][next]
# Converts a binary number into a decimal
# Modify to verify that the inputted number is valid.
# Added test functions that programmatically test if the function is behaving
# appropriately.
# By CSCI111
import sys
def main():
# Read in the binary number as a string -- why?
num = input("Enter the binary #: ")
# --------- Validate the user input ----------
if not isBinary(num):
print(num, "is not a valid binary number. Please try again.")
sys.exit()
decVal = binaryToDecimal(num)
print("The decimal value for", num, "is", decVal)
def binaryToDecimal(binnum):
"""
Converts the binary number to a decimal number
Precondition: binary, a string that is a binary number
Postcondition: returns the decimal value of the binary number
"""
# accumulate the decimal value in this variable
decVal = 0
# go through the positions in the string
for pos in range(len(binnum)):
# num[pos] is a string; need to convert to an int
bit = int(binnum[pos])
# calculate which "place" the current bit is at
place = 2**(len(binnum)-pos-1)
# add to the decimal value
decVal += place * bit
return decVal
def isBinary(candidate):
"""
Precondition: candidate is a string
Postcondition: returns True iff candidate is a valid binary string
"""
# check that it has all digits (no letters)
if not candidate.isdigit():
return False
# Make sure that the inputted number only contains 0s and 1s
for digit in candidate:
if digit != "0" and digit != "1":
return False
return True
def testIsBinary():
"""
Test the isBinary function.
Displays the correctness or incorrectness of the function.
Does not return anything.
"""
# ----------- Test where the result should be True ---------
testBinaryTrue = ["0", "1", "10", "1001", "10000"]
for test in testBinaryTrue:
result = isBinary(test)
if result:
print(test, "successfully identified as binary")
else:
print("**ERROR! **", test, "considered not binary")
# ----------- Test where the result should be False ---------
testBinaryFalse = ["a", "3", "-100", "123"]
for test in testBinaryFalse:
result = isBinary(test)
if not result:
print(test, "successfully identified as not binary")
else:
print("**ERROR! **", test, "considered binary")
# ------------ Alternatively, have a list of inputs and expected ----
# Question: How difficult is it to verify additional test cases?
inputs = [ "0", "1", "10", "1001", "10000", "a", "3", "-100", "123"]
expectedResults = [ True, True, True, True, True, False, False, False, False]
for pos in range(len(inputs)):
testInput = inputs[pos]
if isBinary(testInput) != expectedResults[pos]:
print("Error on isBinary(", testInput, ")")
print("Expected", expectedResults[pos], "but got", isBinary(testInput))
def testBinaryToDecimal():
"""Test the binaryToDecimal function.
Displays the correctness or incorrectness of the function.
Nothing is returned."""
paramInputs = ["0", "1", "10", "1001", "10000"]
expectedResults = [ 0, 1, 2, 9, 16]
for index in range(len(paramInputs)):
paramInput = paramInputs[index]
expectedResult = expectedResults[index]
actualResult = binaryToDecimal(paramInput)
if actualResult != expectedResult:
print("**ERROR! **", paramInput, "should be", expectedResult)
print("Instead, got", actualResult)
else:
print("Success on binary to decimal conversion for", paramInput, "-->", actualResult)
testIsBinary()
testBinaryToDecimal()
flow_example.py 4/9
[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 5/9
[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 6/9
[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 7/9
[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()
main()
wheeloffortune.wfiles_functions.py 8/9
[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 9/9
[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.