Contents
- birthyear3.py
- birthyear.py
- file_handle.py
- yearborn.py
birthyear3.py 1/4
[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/4
[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/4
[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()
yearborn.py 4/4
[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.