Contents

  1. avgData.py
  2. cleanRoster.py
  3. file_handle.py
  4. file_write.py
  5. game.py
  6. yearborn.py

avgData.py 1/6

[
top][prev][next]
# Computes the average high temperature from a file that contains the daily
# high temperatures for last year at one location.
# CSCI 111

DATAFILE="data/virginia.dat"

state = input("What state are you interested in? ")

DATAFILE = "data/" + state + ".dat"

# open the file
tempFile = open(DATAFILE, "r")

# temperature accumulator
tempSum = 0
# count for how many temperatures?
tempCount = 0

# Read what's in the file: 
# go through each line of the file
for line in tempFile:
    # extract the temperature
    temperature = float(line)
    # add up all the temperature
    tempSum += temperature
    # update the count
    tempCount += 1

# close the file
tempFile.close()

# find the average of what's in the file
# divide the sum of the temperatures by the total number of temperatures
averageTemp = tempSum/tempCount

# round average to two decimal places, display it
print("The average temperature in {:s} is {:.2f}".format(DATAFILE, averageTemp))

cleanRoster.py 2/6

[
top][prev][next]
# Reads in the file "data/years.dat", which has the form:
# name Ugr:class
#
# Removes the "Ugr:" prefix on the class and writes the data to the file 
# in the form:
# name class
#
# (If time, format the data into nice columns.  What would be a 
# good widths for the data?)
#
# By CSCI 111

INPUT_FILE="data/years.dat"
OUTPUT_FILE="data/roster.dat"

inputFile = open(INPUT_FILE, "r")
outputFile = open(OUTPUT_FILE, "w")

# go through each line in INPUT_FILE
for line in inputFile:
    # and get rid of Ugr:
    updatedLine = line.replace("Ugr:", "")
    # put that updated line in the OUTPUT_FILE
    outputFile.write(updatedLine)
    
    # TODO: format the line nicely

inputFile.close()
outputFile.close()

file_handle.py 3/6

[
top][prev][next]
# Demonstrate file handling exception
# Sara Sprenkle

import sys

def main():
    infileName = input("What file do you want to read? ")
    
    # put the "correct"/"usual" behavior within the try
    try:
        inFile = open(infileName, "r")
        # normally, we would do some sort of processing of the file here.
        inFile.close()
    except IOError as exc: # exc is the name of the thrown exception
        print("Error reading \"" + infileName + "\".")
        # could be a variety of different problems, so print out
        # the exception
        print(exc)
        sys.exit(1)

    outfileName = input("What file do you want to write? ")
   
    try:
        outFile = open(outfileName, "w")
        # normally, we would do some sort of processing of the file here.
        outFile.close()
    except IOError as exc:
        print("Error writing \"" + outfileName + "\".")
        print(exc)
        # no need to exit here because there is nothing else to do.
    
main()

file_write.py 4/6

[
top][prev][next]
# Writes content from a user to a file
# by Sara Sprenkle

PROMPT = "Enter the next line in the file: "

outfilename = input("What is the name of your output file? ")
numLines = eval(input("How many lines do you want to write? "))

# create a new file object, in "write" mode
dataFile = open(outfilename, "w")

for x in range(numLines):
    userinput = input(PROMPT)
    # write the user's input to the file
    dataFile.write(userinput)
    # write a newline after each input from the user
    dataFile.write("\n")

# close the file with the method "close"
dataFile.close()

game.py 5/6

[
top][prev][next]
# A module of useful functions for games.
# By Sara Sprenkle

from random import *

SIDES=6

def rollDie(sides):
    """
    Given the number of sides on the die (a positive integer),
    simulates rolling a die by returning the rolled value.
    """
    return randint(1,sides)


def rollMultipleDice(numDice, sides):
    """
    Given the number of dice (numDice, a positive integer) and
    the number of sides on the dice (sides, a positive integer),
    simulates rolling those dice and returns the sum of the rolled
    values.
    """
    diceTotal = 0
    for x in range(numDice):
        diceTotal += rollDie(sides)
    return diceTotal


def testRollDie():
    """
    Tests the rollDie function.  Does not guarantee correctness,
    but gives us some confidence in the function's correctness.
    """
    numTests = 0
    numSuccesses = 0

    for sides in range(1, 13):
        numTests += 1
        roll = rollDie(sides)
        if roll < 1 or roll > sides:
            print("Error rolling die with", sides, "sides.  Got", roll)
        else:
            numSuccesses += 1
    print("Test passed", numSuccesses, "out of", numTests, "tests")


def testRollMultipleDice():
    """
    Tests the rollMultipleDice function.  Does not guarantee correctness,
    but gives us some confidence in the function's correctness.
    """
    numTests = 0 
    numSuccesses = 0
    for numDie in range(1, 5):
        for sides in range(1, 13):
            numTests += 1
            roll = rollMultipleDice( numDie, sides)
            if roll < numDie or roll > numDie * sides:
                print("Error rolling", numDie, "dice with", sides, "sides.  Got"
, roll)
            else:
                numSuccesses += 1
    print("Test passed", numSuccesses, "out of", numTests, "tests")

#if __name__ == "__main__":
testRollDie()
testRollMultipleDice()

yearborn.py 6/6

[
top][prev][next]
# Demonstrate validating user input
# Modified from a student's code from lab assignment

import sys

def main():
    #Program mission statement
    print("This program determines your birth year")
    print("given your age and the current year \n")

    try:
        age = int(input("Enter your age: "))
        # note difference if use eval instead of int in above 
        currentyear = int(input("Enter the current year: "))
    except:
        print("ERROR: Your input was not in the correct form.")
        print("Enter integers for your age and the current year")
        sys.exit()
    
    if age < 0 or age > 115:
        print("Come on: you have to be a reasonable age.")
    elif currentyear < 0:
        print("You need to have a positive year.")
    else:
        #Subtract age from current year
        birthyear=currentyear - age
        #Display output to the user
        print("You were either born in", birthyear, "or", birthyear-1)


main()

Generated by GNU Enscript 1.6.6.