Contents

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

cleanRoster.py 1/5

[
top][prev][next]
# Reads in the file "data/years.csv", which has the form:
# lastname,firstname,email,Ugr:class
# 
# Note: .csv extension means "comma-separated values"
#
# Removes the "Ugr:" prefix on the class and writes the data to the file 
# in the form:
# lastname class
#
# (If time, format the data into nice columns.  What would be 
# good widths for the data?)
#
# By CSCI 111

INPUT_FILE="data/years.csv"
OUTPUT_FILE="data/roster.txt"

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

# read through each line of the input file
for line in inputFile:
    # split the line on ,
    infoList = line.split(",")
    
    # get the last name (first index) and the class year (last index)
    lastName = infoList[0]
    classYear = infoList[-1] # equivalent to infoList[3]
    # Note that the split does not remove the "\n" from line, 
    # so classYear will end with a newline character
    
    # remove Ugr: from the classname
    classYear = classYear.replace("Ugr:", "")
    # equivalent to classYear = classYear[4:]
    # or split on ":"
    
    # write data to the output file
    outputFile.write(lastName + " " + classYear)
    # if classYear did not end with a newline character,
    # we'd need to add a newline character here.

# close the files
inputFile.close()
outputFile.close()

file_handle.py 2/5

[
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 3/5

[
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 4/5

[
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 5/5

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