Contents
- file_handle.py
- loop.py
- pick4num_wfunctions.py
- therapist.py
- while.py
- whilevsfor.py
- yearborn.py
file_handle.py 1/7
[top][prev][next]
# Demonstrate handling file exceptions
# Sara Sprenkle
import sys
def main():
infileName = input("What file do you want to read? ")
try:
inFile = open(infileName, "r")
# should probably be doing something in here.
# Just for demonstrating handling exceptions
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")
# should probably be doing something in here.
# Just for demonstrating handling exceptions
outFile.close()
except IOError as exc:
print("Error writing \"" + outfileName + "\".")
print(exc)
main()
loop.py 2/7
[top][prev][next]
# What does this loop do?
# Sara Sprenkle
count = 1
while count > 0:
print(count)
count += 1
pick4num_wfunctions.py 3/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
# NEW: Updated to demonstrate a default parameter to a function.
# 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="####"
def main():
pickedNum = input("What is your pick? (Format: " + NUMFORMAT + ") ")
###### handle bad input ######
error = False
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()
winningNum = generateWinningNum()
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.")
def generateWinningNum(numNums=NUM_PICKS):
"""
generates a winning number based on constants defined for ...
returns a string of random numbers of length numNums;
default numNums is NUM_PICKS
"""
# Generate the random number; accumulator design pattern
winNum = "" # start the winning number as the empty string
for i in range(numNums):
# generate a random number
# add the random number to the previous random number
winNum += str(randint(MIN_VALUE,MAX_VALUE))
return winNum
main()
therapist.py 4/7
[top][prev][next]
# The Simple Therapist
# CSCI 111
print("-"*60)
print("Welcome to computerized therapy!")
print("You will get your money's worth.")
print("Our session is over when you have nothing more to tell me.")
print("-"*60)
user_input = input("Tell me what's wrong.\n")
while user_input != "":
user_input = input("How does that make you feel?\n")
print("Thank you! Come again!")
while.py 5/7
[top][prev][next]
# Demonstrates a simple while loop
# Sara Sprenkle
i = 0
while i < 10 :
print("i equals", i)
i+=1
print("Done", i)
whilevsfor.py 6/7
[top][prev][next]
# Compares a while loop with a for loop
# by Sara Sprenkle
# ---------- WHILE LOOP ----------
print("While Loop Demo")
i=0
while i < 10:
print("i equals", i)
i += 1
print("Done", i)
# ---------- FOR LOOP ----------
print("\nFor Loop Demo")
for i in range(10):
print("i equals", i)
print("Done", i)
# To give exactly the same output as the while loop, would need to print out i+1
yearborn.py 7/7
[top][prev][next]
# Demonstrate validating user input using exception handling
# Sara Sprenkle
import sys
def main():
#Program mission statement
print("This program determines your birth year")
print("given your age and the current year \n")
# enforce valid input
try:
age = eval(input("Enter your age: "))
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.4.