PY4E 作业练习 答案代码 exercises answer code

以下是《Python for Everybody——Exploring Data Using Python 3》Charles R. Severance 的教材部分章节的习题的代码,均可直接复制保存成 *.py 文件执行。随缘更新 😃

2020.12.08 三天打鱼两个月晒网,最近比较懒,工作也比较忙,果然忘了markdown用法了
2022.5.3 谁能想到过了一年多我还没学完🤣最近有了宝宝,时间变得紧张并零碎

Chapter 3

Exercise 1: Rewrite your pay computation to give the employee 1.5 times the hourly rate for hours worked above 40 hours.

Enter Hours: 45
Enter Rate: 10
Pay: 475.0

x = input('Enter Hours: ')
y = input('Enter Rate: ')
hours = float(x)
rate = float(y)
if hours > 40:
    pay = 40*rate + (hours-40)*rate*1.5
    print('Pay: %s' %pay)
else:
    pay = hours*rate
    print('Pay: %s' %pay)
input()    #.py文件执行时防止闪退,相当于任意输入后退出

Exercise 2: Rewrite your pay program using try and except so that your program handles non-numeric input gracefully by printing a message and exiting the program. The following shows two executions of the program:

x = input('Enter Hours: ')
try:
    hours = float(x)
except:
    print('Error, please enter numeric input')
    input()         #暂停,显示错误提示
    sys.exit()      #退出

y = input('Enter Rate: ')
try:
    rate = float(y)
except:
    print('Error, please enter numeric input')
    input()         #暂停,显示错误提示
    sys.exit()      #退出

if hours > 40:
    pay = 40*rate + (hours-40)*rate*1.5
    print('Pay: %s' %pay)
else:
    pay = hours*rate
    print('Pay: %s' %pay)
input()

Exercise 3: Write a program to prompt for a score between 0.0 and 1.0. If the score is out of range, print an error message. If the score is between 0.0 and 1.0, print a grade using the following table:

ScoreGrade
>= 0.9A
>=0.8B
>=0.7C
>=0.6D
<0.6F
OtherBad score
多种并列条件,需用 elifif并列,每个条件只选其一执行;如果全用 if 则各个条件依次执行,比如score=0.95,各 if 条件均满足,最后输出结果为D,这是错误的!
inp = input('Enter Score: ')
try:
    score = float(inp)
except:
    print('Bad score')
    input()

if score >= 0 and score <= 1:
    if score >= 0.9:
        grade = 'A'
    elif score >= 0.8:
        grade = 'B'
    elif score >= 0.7:
        grade = 'C'
    elif score >= 0.6:
        grade = 'D'
    else:
        grade = 'F'
else:
    grade = 'Bad score'
print(grade)
input()  

Chapter 4

Exercise 6: Rewrite your pay computation with time-and-a-half for over-time and create a function called computepay which takes two parameters (hours and rate).
Enter Hours: 45
Enter Rate: 10
Pay: 475.0

注意:函数定义必须在第一次调用之前执行!故定义部分必须前置。

def computepay(a, b):
    if a > 40 :
        return 40*b + (a-40)*b*1.5
    else:
        return a*b


x = input('Enter Hours: ')
try:
    hours = float(x)
except:
    print('Error, please enter numeric input')
    input()         #暂停,显示错误提示
    sys.exit()      #退出

y = input('Enter Rate: ')
try:
    rate = float(y)
except:
    print('Error, please enter numeric input')
    input()         #暂停,显示错误提示
    sys.exit()      #退出

pay = computepay(hours, rate)
print('Pay: %s' %pay)
input()

Exercise 7: Rewrite the grade program from the previous chapter using a function called computegrade that takes a score as its parameter and returns a grade as a string.

def computegrade(score):
    if score >= 0 and score <= 1:
        if score >= 0.9:
            return 'A'
        elif score >= 0.8:
            return 'B'
        elif score >= 0.7:
            return 'C'
        elif score >= 0.6:
            return 'D'
        else:
            return 'F'
    else:
        return 'Bad score'

inp = input('Enter Score: ')
try:
    score_num = float(inp)
except:
    print('Bad score')
    input()

print(computegrade(score_num))
input()

Chapter 5

Exercise 1: Write a program which repeatedly reads numbers until the user enters “done”. Once “done” is entered, print out the total, count, and average of the numbers. If the user enters anything other than a number, detect their mistake using try and except and print an error message and skip to the next number.

total = 0
count = 0
average = 0
while True:
    inp = input('Enter a number:')
    if inp == 'done':  # =是赋值,==才是定值
        break
    try:
        inp = float(inp)
    except:
        print('%s is not a number' % inp)
        continue
    total = total + inp
    count = count + 1
    average = total / count
print('Total: %s Count: %s Average: %s' % (total, count, average))
input()

Exercise 2: Write another program that prompts for a list of numbers as above and at the end prints out both the maximum and minimum of the numbers instead of the average.

Max = None
Min = None
while True:
    inp = input('Enter a number: ')
    if inp == 'done':
        break
    try:
        inp = float(inp)
    except:
        print('%s is not a number' % inp)
        continue
    if Max is None or Max < inp: # None是空值,不能与实数比较,故必须加上 is None, 否则会报错
        Max = inp
    if Min is None or Min > inp:
        Min = inp
print('Maximum:', Max, "Minimum:", Min)
input()

Chapter 6

Exercise 1: Write a while loop that starts at the last character in the string and works its way backwards to the first character in the string, printing each letter on a separate line, except backwards.

string = input('Enter the string:')
index = 0
while index > -len(string):
    index = index - 1   #从-1由末位往前倒退
    print(string[index])
input()
string = input('Enter the string:')
index = len(string) - 1   #从字符串总长度由大到小倒退
while index >= 0:
    print(string[index])
    index = index -1
input()

Exercise 2: Given that fruit is a string, what does fruit[:] mean?

If you omit the first index (before the colon), the slice starts at the beginning of the string. If you omit the second index, the slice goes to the end of the string

Obviously, fruit[:] will traversal through the entire string.

>>> fruit = 'banana'
>>> fruit[:]
'banana'

Exercise 3: Encapsulate this code in a function named count, and generalize it so that it accepts the string and the letter as arguments.

string = input('Enter the string:')
letter = input('Enter the letter you want to count:')
def count(string, letter):
    letter_num = 0
    for i in string:
        if i == letter:
            letter_num = letter_num + 1
    return letter_num   #函数需要有返回值,否则函数无输出。注意return与for对齐
print(count(string, letter))     

Exercise 4: Exercise 4: There is a string method called count that is similar to the function in the previous exercise. Read the documentation of this method at:[https://docs.python.org/library/stdtypes.html#string-methods] Write an invocation that counts the number of times the letter a occurs in “banana”.

word = 'banana'
Num = word.count('a')
print(Num)

Exercise 5: Take the following Python code that stores a string:
str = 'X-DSPAM-Confidence:0.8475'
Use find and string slicing to extract the portion of the string after the colon character and then use the float function to convert the extracted string into a floating point number.

str = 'X-DSPAM-Confidence:0.8475'
colonpos = str.find(':')
data = str[colonpos+1: ]
print(float(data))

Chapter 7

Exercise 1: Write a program to read through a file and print the contents of the file (line by line) all in upper case. Executing the program will look as follows:

python shout.py
Enter a file name: mbox-short.txt
FROM [email protected] SAT JAN  5 09:14:16 2008
RETURN-PATH: <[email protected]>
RECEIVED: FROM MURDER (MAIL.UMICH.EDU [141.211.14.90])
     BY FRANKENSTEIN.MAIL.UMICH.EDU (CYRUS V2.3.8) WITH LMTPA;
     SAT, 05 JAN 2008 09:14:16 -0500
fname = input('Enter a file name: ')
try:
    fhand = open(fname)
except:
    print('File cannot be opened: ', fname)
    exit()
for line in fhand:
    line = line.rstrip() #删除尾部空格
    if line == '':       #若该行为空则不打印
        continue
    print(line.upper())  #转换为大写

Exercise2: Write a program to prompt for a file name, and then read through the file and look for lines of the form:

X-DSPAM-Confidence: 0.8475

When you encounter a line that starts with “X-DSPAM-Confidence:” pull apart the line to extract the floating-point number on the line. Count these lines and then compute the total of the spam confidence values from these lines. When you reach the end of the file, print out the average spam confidence.

fname = input('Enter a file name: ')
try:
    fhand = open(fname)
except:
    print('File cannot be opened: ', fname)
    exit()
i = 0
spamconf = 0
for line in fhand:
    if line.startswith('X-DSPAM-Confidence:'):
        colonpos = line.find(':')     #找出冒号所在位置
        data = line[colonpos + 1:]    #提取冒号后的数字,此时仍是字符串,需通过float()转换为浮点数
        i = i + 1
        spamconf = spamconf + float(data)
print('Average spam confidence: ', spamconf/i)

Exercise3: Sometimes when programmers get bored or want to have a bit of fun, they add a harmless Easter Egg to their program. Modify the program that prompts the user for the file name so that it prints a funny message when the user types in the exact file name “na na boo boo”. The program should behave normally for all other files which exist and don’t exist. Here is a sample execution of the program:

python egg.py
Enter the file name: mbox.txt
There were 1797 subject lines in mbox.txt

python egg.py
Enter the file name: missing.tyxt
File cannot be opened: missing.tyxt

python egg.py
Enter the file name: na na boo boo
NA NA BOO BOO TO YOU - You have been punk'd!
fname = input('Enter a file name: ')
if fname == 'na na boo boo':
    print("NA NA BOO BOO TO YOU - You have been punk'd!")
    exit()
try:
    fhand = open(fname)
except:
    print('File cannot be opened: ', fname)
    exit()
i = 0
for line in fhand:
    if line.startswith('Subject:'):
        i = i + 1
print('There were %s subject lines in %s' % (i, fname))
  • 9
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值