Week03 Exercise
Rewrite your pay program using try and except so
that your program handles non-numeric input gracefully.
Enter Hours: 20
Enter Rate: nine
Error, please enter numeric input
try:
inp = raw_input('Enter Hours: ')
hours = float(inp)
inp = raw_input('Enter Rate: ')
rate = float(inp)
except:
print "Error,please enter numeric input"
quit()
if hours <= 40:
pay = rate * hours
else:
pay = rate * 40 + ( hours - 40 ) * 1.5 * rate
print pay
Week03 Assignment
Write a program to prompt for a score between 0.0 and 1.0.
If the score is out of range, print an error.
If the score is between 0.0 and 1.0, print a grade using the following table:
Score Grade
>= 0.9 A
>= 0.8 B
>= 0.7 C
>= 0.6 D
< 0.6 F
If the user enters a value out of range, print a suitable error message and exit. For the test, enter a score of 0.85.
try:
inp = raw_input('Please enter a score: ')
score = float(inp)
except:
print "Error, please enter a floated score"
quit()
if score > 0.9:
print 'A'
elif score > 0.8:
print 'B'
elif score > 0.7:
print 'C'
elif score > 0.6:
print 'D'
else:
print 'F'
Week04 Assignment
Rewrite your pay computation with time-and-a-half
for overtime and create a function called computepay
which takes two parameters ( hours and rate).
Enter Hours: 45
Enter Rate: 10
Pay: 475.0
def computepay(h,r):
print "in computepay",h,r
if h <= 40:
p = r * h
else:
p = r * 40 + ( r * 1.5 * (h-40) )
print "Finished with computepay",p
return p
try:
inp = raw_input("Enter Hours: ")
hours = float(inp)
inp = raw_input("Enter Rate: ")
rate = float(inp)
except:
print "Error, please enter numeric input."
quit()
print "In the main code",rate,hours
pay = computepay(hours,rate)
print "We are back",pay
Week05 Assignment
Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'.
Once 'done' is entered, print out the largest and smallest of the numbers. If the user
enters anything other than a valid number catch it with a try/except and put out an
appropriate message and ignore the number. Enter the numbers from the book for problem 5.1
and Match the desired output as shown.
largest = None
smallest = None
num_list = []
while True:
num = raw_input("Enter a number: ")
if num == "done" : break
try:
num_list.append(int(num))
except:
print "Invalid input"
#find largest and smallest
for i in num_list:
if largest == None:
largest = i
else:
if largest < i:
largest = i
if smallest == None:
smallest = i
else:
if smallest > i:
smallest = i
print "Maximum is", largest
print "Minimum is", smallest
Week06 Assignment
Parse the string: 'X-DSPAM-Confidence: 0.8475'
x = 'X-DSPAM-Confidence: 0.8475'
pos = x.find(':')
num = float(x[pos+1:].lstrip())
print num,type(num)
Week07 Assignment
Write a program to read through a file and print contents of the file all in upper case. The file: http://www.py4inf.com/code/mbox-shrot.txt
fname = raw_input('Enter a file name:')
fhand = open(fname);
for line in fhand:
line = line.rstrip()
line = line.upper()
print line
Week07 Assignment2
Write a program that prompts for a file name, then opens that file and reads through the file, looking for lines of the form:
X-DSPAM-Confidence: 0.8475
Count these lines and extract the floating point values from each of the lines and compute the average of those values and produce an output as shown below. You can download the sample data at http://www.pythonlearn.com/code/mbox-short.txt when you are testing below enter mbox-short.txt as the file name.
# Use the file name mbox-short.txt as the file name
#fname = raw_input("Enter file name: ")
fh = open("d:/mbox-short.txt")
cnt = 0
sum = 0
for line in fh:
if not line.startswith("X-DSPAM-Confidence:") : continue
cnt = cnt + 1
sum = sum + float(line.split(':')[1].lstrip())
print "Average spam confidence:", sum / cnt
Week08 Assignment
open the file romeo.txt and read it line by line.
For each line, split the line into a list of words using the split() function.
The program should build a list of words. For each word on each line check to see if the word is already in the list and if not append it to the list. When the program completes, sort and print the resulting words in alphabetical order.
You can download the sample data at http://www.pythonlearn.com/code/romeo.txt
fname = '/home/loongson/py4/romeo.txt'
fh = open(fname)
lst = list()
for line in fh:
line = line.rstrip()
words = line.split()
for word in words:
if word not in lst:
lst.append(word)
lst.sort()
print lst
Week08 Assignment02
Open the file mbox-short.txt and read it line by line. When you find a line that starts with 'From ' like the following line:
From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
You will parse the From line using split() and print out the second word in the line (i.e. the entire address of the person who sent the message). Then print out a count at the end. Hint: make sure not to include the lines that start with 'From:'.
You can download the sample data at http://www.pythonlearn.com/code/mbox-short.txt
fname = '/home/loongson/py4/mbox-short.txt';
fh = open(fname)
count = 0
for line in fh:
line = line.strip()
words = line.split()
if len(words):
if words[0] == 'From:':
count = count + 1
print words[1]
print "There were",count,"lines in the file with From as the first word"
Week10 Assignment01
统计一片文章出现频率最高的10个词
fhand = open('d:/romeo-full.txt');
counts = dict()
for line in fhand:
words = line.split()
for word in words:
counts[word] = counts.get(word,0) + 1
flipped = list()
for key,val in counts.items():
newtup = (val,key)
flipped.append(newtup)
flipped.sort(reverse=True)
for val,key in flipped[:10]:
print key,val