Contents

  1. birthyear3.py
  2. birthyear.py
  3. file_handle.py
  4. mystery.py
  5. tictactoe.py
  6. twod_exercises.py
  7. yearborn.py

birthyear3.py 1/7

[
top][prev][next]
# Demonstrate validating user input
# Made from a student's code from Lab 1

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

    age = getPosIntegerInput("Enter your age: ")
    currentyear = getPosIntegerInput("Enter the current year: ")
    
    if age > 115:
        print "That is not a reasonable age"
    else:
        birthyear=currentyear - age
        #Display output to the user
        print "You were either born in", birthyear, "or", birthyear-1


def getPosIntegerInput(prompt):
    """Repeatedly prompts the user for input until the user
    enters a positive integer."""
    while True: 
        try:
            value=input(prompt)
            if value > 0:
                return value
            else:
                print "Number is out of range"
        except: 
            print
            print "ERROR: Your input was not in the correct format."
            print "You must enter a positive integer value"

main()

birthyear.py 2/7

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

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

    age=input("Enter your age: ")
    currentyear=input("Enter the current year: ")
    
    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()

file_handle.py 3/7

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

import sys

def main():
    infileName = raw_input("What file do you want to read? ")
    
    try:
        inFile = file(infileName, "r")
    except IOError, 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 = raw_input("What file do you want to write? ")
   
    try:
        outFile = file(outfileName, "w")
    except IOError, exc:
        print "Error writing \"" + outfileName + "\"."
        print exc
    
 
 
main()

mystery.py 4/7

[
top][prev][next]
# Practice with 2D lists
# by Sara Sprenkle

def main():
    matrix = createMatrix()
    print "Before:"
    print matrix
    mystery(matrix)
    print "After:"
    print matrix

def mystery(a):
    """ "run" this on A, at right """
    for row in range( len(a) ):
        for col in range( len(a[0]) ):
            if row == col:
                a[row][col] = 42
            else:
                a[row][col] += 1

def createMatrix():
    a0 = range(1,5)
    a1 = range(5,9)
    a2 = range(9,13)
    a = []
    a.append(a0)
    a.append(a1)
    a.append(a2)
    return a

main()

tictactoe.py 5/7

[
top][prev][next]
# Practice using 2D lists using Tic-Tac-Toe
# by Sara Sprenkle

def main():
    board = createBoard()
    
    print "Original Board:"
    displayBoard(board)
    print
    
    print "X goes to 1, 1:"
    pickPos(board, 1, 1, "x")
    displayBoard(board)
    print
    
    print "O goes to 0, 2:"
    pickPos(board, 0, 2, "o")
    displayBoard(board)


def createBoard():
    board = []
    for row in xrange(3):
        row = []
        for col in xrange(3):
            row.append(" ")
        board.append(row)
    return board

def displayBoard(board):
    """ Display the tic-tac-toe board in a nice way """
    for row in xrange(2):
        for col in xrange(2):
            print "%1s |" % board[row][col],
        print "%1s" % board[row][2]
        print "-"*9
    for col in xrange(2):
        print "%1s |" % board[2][col],
    print "%1s" % board[2][2]
        

def pickPos(board, row, col, symbol):
    # Should handle that position is already taken
    board[row][col] = symbol
   

main()


twod_exercises.py 6/7

[
top][prev][next]
# Practice with 2D Lists
# Sara Sprenkle

def main():
    rows = input("How many rows? ")
    columns = input("How many columns? ")

    print
    print "Correct Matrix Creation:"
    print '-'*30
    matrix = create2DList(rows, columns)
    print matrix

    print "\nAssigning matrix[1][2]=3"
    matrix[1][2] = 3
    print "Result: "
    print matrix

    print
    print "*"*50
    print "Incorrect Matrix Creation:"
    print '-'*30

    matrix = noCreate2DList(rows, columns)
    print matrix

    print "\nAssigning matrix[1][2]=3"
    print "Result: "
    matrix[1][2] = 3
    print matrix


def create2DList(rows, cols):
    """Returns a two-dimensional list filled with 0s that is 'rows' tall and
    'cols' wide."""
    twodlist = []
    for row in xrange(rows):
        row = []
        for col in xrange(cols):
            row.append(0)
        twodlist.append(row)
    return twodlist

def noCreate2DList(rows, cols):
    """Does not create a 2D list because each 'row' points to the same point in
    memory."""
    
    twodlist = []
    onerow = []
    for col in xrange(cols):
        onerow.append(0)
    for row in xrange(rows):
        twodlist.append(onerow)
        
    return twodlist

    

main()

yearborn.py 7/7

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

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

    try:
        age = input("Enter your age: ")
        currentyear = 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"
        return
    
    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.4.