Contents

  1. daysOfWeek.py
  2. fibs2.py
  3. fibs.py
  4. friends.py
  5. handling_bad_input.py
  6. pick4num.py
  7. wheeloffortune.py

daysOfWeek.py 1/7

[
top][prev][next]
# Example illustrating list operations: concatenation and iteration
# by Sara Sprenkle

weekDays = ["Mon", "Tue", "Wed", "Thu", "Fri"]
weekendDays = ["Sat", "Sun"]

# combine two lists into one
daysOfWeek = weekDays + weekendDays

print("The Days of the Week:")

# iterate through elements of list
for day in daysOfWeek:
    print(day)

print("\nAGAIN!")

# iterate through positions of list
for x in range(len(daysOfWeek)):
    print(daysOfWeek[x])

print()  
# reorganizing days of week to start on a Sunday
daysOfWeek = weekendDays[-1:] + weekDays + weekendDays[:1]

extractWeekend = daysOfWeek[:1] + daysOfWeek[-1:]
print("Extracted weekend: ", extractWeekend)

extractWeekend2 = [daysOfWeek[0], daysOfWeek[-1]]
print("Extracted weekend: ", extractWeekend2)

notExtractedWeekend = daysOfWeek[0] + daysOfWeek[-1]
print("Does not work: ", notExtractedWeekend)

fibs2.py 2/7

[
top][prev][next]
# Example of creating a list of the appropriate size
# Computes the first SIZE Fibonacci numbers
# Sara Sprenkle

SIZE = 15

print("This program generates the first", SIZE, "Fibonacci numbers")

# creates a list of size 15, containing all 0s
fibs = [0]*15

fibs[0] = 1
fibs[1] = 1

for x in range(2, len(fibs)):
    newfib = fibs[x-1]+fibs[x-2]
    fibs[x] = newfib

print(fibs)

# To print out the list, each element on a separate line
#for num in fibs:
#    print num

fibs.py 3/7

[
top][prev][next]
# Example of appending to a list
# Computes the first SIZE Fibonacci numbers
# Sara Sprenkle

SIZE = 15

print("This program generates the first", SIZE, "Fibonacci numbers")

# create an empty list
fibs = []

# append the first two Fibonacci numbers
fibs.append(1)
fibs.append(1)

# compute the next 13 Fibonacci numbers
for x in range(2,SIZE):
    newfib = fibs[x-1]+fibs[x-2]
    fibs.append(newfib)


# print the Fibonacci numbers as a list
print(fibs)


# Tradeoff of using more space (the list) for easier implementation

friends.py 4/7

[
top][prev][next]

friends = ["Alice", "Bjorn", "Cayman", "Duanphen", "Esfir", "Farah"]

for cat in friends[1:]:
    print("I know " + cat + ".")
    print("%s is a friend of mine." % (cat))
print("Those are the people I know.")

# alternative
#for pos in range(1, len()):

handling_bad_input.py 5/7

[
top][prev][next]
# Demonstrates a better way to handle multiple bad inputs
# Extra program, not covered in class.  Another example to
# help improve your coding skills.
# by Sara Sprenkle

WMIN = 2
WMAX = 80
HMIN = 2
HMAX = 20

WIDTH_INPUT = "Enter a width (" + str(WMIN) + "-" + str(WMAX) + "): "
HEIGHT_INPUT = "Enter a height (" + str(HMIN) + "-" + str(HMAX) + "): "

width = eval(input(WIDTH_INPUT))
height = eval(input(HEIGHT_INPUT))

error = False
errorMessage = "\nError: \n"

# What does the following code do?
# Why do I consider this a better way to handle multiple bad inputs?
if width < WMIN or width > WMAX:
    error = True
    errorMessage += "\tWidth (" +str(width) + ") is not within range (" + str(WMIN) + "-" + str(WMAX) + ")\n"
    
if height < HMIN or height > HMAX:
    error = True
    errorMessage += "\tHeight (" +str(height) + ") is not with range ("+ str(HMIN) + "-" + str(HMAX) + ")\n"
    
if error:
    print(errorMessage)    



pick4num.py 6/7

[
top][prev][next]
# Simulate Pick 4 lottery game - selecting ping pong balls at random
# Modified to figure out if the user entered the winning number
# Demonstrates what I consider to be better error handling.
# By CSCI111

from random import *
import sys

# define constants that are easy to change so that our
# program is flexible
NUM_PICKS = 4
MIN_VALUE = 0
MAX_VALUE = 9

NUMFORMAT="####"

pickedNum = input("What is your pick? (Format: " + NUMFORMAT + ") ")

######  handle bad input ######
error = True
errorMessage = "Error:\n"

# Check that user enters a string that contains only numbers
if not pickedNum.isdigit():
    errorMessage += "\tYour number must contain only numbers\n"
    error = True

# User enters a number that is not four digits long
if len(pickedNum) != 4:
    errorMessage += "\tYour number must contain four numbers"
    error = True
    
if error:
    print(errorMessage)
    sys.exit()
    
# Generate the random number
winningNum = "" # start it as empty

for i in range(NUM_PICKS):
    # generate a random number
    # add the random number to the previous random number
    winningNum += str(randint(MIN_VALUE,MAX_VALUE))

print("The winning Pick 4 lottery number is ", winningNum)
print()

if winningNum == pickedNum:
    print("Congratulations!  You are very lucky and rich!")
    print("We should be friends!")
else:
    print("Sorry, you lost.")

wheeloffortune.py 7/7

[
top][prev][next]
# Wheel of Fortune
# There is a lot of stuff that we don't know how to do yet,
# but there is also a lot of stuff that you DO!
# By Sara Sprenkle

PHRASE="Darpa Urban Challenge".upper()
# PHRASE = ""
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 )

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

print ("The puzzle:", displayedPuzzle)

print()
print ("Let's get started!")

# how many guesses it took to get it right
numGuesses = 1

guess = input(PROMPT)

while guess.lower() != PHRASE.lower() :
    if len(guess) == 1 and guess.isalpha(): 
        numOccurences = PHRASE.count(guess) + PHRASE.count(guess.swapcase())
        if numOccurences > 0:
            print ("There are", numOccurences, guess + "'s", "in the phrase")
            # fill in puzzle
            updatedpuzzle=""
            for pos in range(len(PHRASE)):
                if PHRASE[pos] == guess or PHRASE[pos] == guess.swapcase():
                    updatedpuzzle += PHRASE[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")


Generated by GNU Enscript 1.6.6.