《Python编程:从入门到实践》 第10章 文件和异常 练习题


0 前言

《Python编程:从入门到实践》 第10章 文件和异常 练习题

1 加法运算

练习10-6 加法运算

提示用户提供数值输入时,常出现的一个问题是,用户提供的是文本而不是数字。在这种情况下,当你尝试将输入转换为整数时,将引发TypeError异常。编写一个程序,提示用户输入两个数字,再将它们相加并打印结果。在用户输入的任何一个值不是数字时都捕获TypeError异常,并打印一条友好的错误消息。对你编写的程序进行测试:先输入两个数字,再输入一些文本而不是数字。

练习10-7 加法计算器

将你为完成练习10-6而编写的代码放在一个while循环中,让用户犯错(输入的是文本而不是数)后能够继续输入数。

自编程序

print("Give me two numbers, and I will sum them.")
print("Enter 'q' to quit.")

while True:
    first_num = input("\nFirst number: ")
    if first_num == 'q':
        break

    second_num = input("Second number: ")
    if second_num == 'q':
        break

    try:
        num1 = int(first_num)
        num2 = int(second_num)
    except ValueError:
        print("Sorry, I need a number.")
    else:
        sum_num = num1 + num2
        print(sum_num)
        

输出如下:

Give me two numbers, and I will sum them.
Enter 'q' to quit.

First number: 1
Second number: 2
3

First number: 4
Second number: 5
9

First number: aa
Second number: 23
Sorry, I need a number.

First number: -100
Second number: 100
0

First number: q

练习10-7 加法计算器 参考答案

print("Enter 'q' at any time to quit.\n")

while True:
    try:
        x = input("\nGive me a number: ")
        if x == 'q':
            break

        x = int(x)

        y = input("Give me another number: ")
        if y == 'q':
            break

        y = int(y)

    except ValueError:
        print("Sorry, I really needed a number.")

    else:
        sum = x + y
        print("The sum of " + str(x) + " and " + str(y) + " is " + str(sum) + ".")

输出如下:

Enter 'q' at any time to quit.

Give me a number: 23
Give me another number: 47
The sum of 23 and 47 is 70.

Give me a number: three
Sorry, I really needed a number.

Give me a number: 3
Give me another number: five
Sorry, I really needed a number.

Give me a number: -12
Give me another number: 20
The sum of -12 and 20 is 8.

Give me a number: q

2 读取文件

练习10-8 猫和狗

创建两个文件——cats.txt和dogs.txt,在第一个文件中至少存储三只猫的名字,在第二个文件中至少存储三条狗的名字。编写一个程序,尝试读取这些文件,并将其内容打印到屏幕上。将这些代码放在一个try-except代码块中,以便在文件不存在时捕获FileNotFound错误,并打印一条友好的消息。将文件之一移到另一个地方,并确认except代码块中的代码将正确地执行。

自编程序

# 创建文件
filenames = ['cats.txt', 'dogs.txt']

for filename in filenames:
    if filename == 'cats.txt':
        with open(filename, 'w') as file_object:
            file_object.write("henry\n")
            file_object.write("clarence\n")
            file_object.write("mildred\n")

    if filename == 'dogs.txt':
        with open(filename, 'w') as file_object:
            file_object.write("willie\n")
            file_object.write("annahootz\n")
            file_object.write("summit\n")

# 读取文件
for filename in filenames:
    try:
        with open(filename, 'r') as file_object:
            contents = file_object.read()

    except FileNotFoundError:
        print("Sorry, I can't find file " + filename)

    else:
        print(filename + ":\n" + contents)

输出如下:

cats.txt:
henry
clarence
mildred

dogs.txt:
willie
annahootz
summit

屏蔽dogs.txt生成代码并移走dogs.txt的输出如下:

cats.txt:
henry
clarence
mildred

Sorry, I can't find file dogs.txt

练习10-8 猫和狗 参考答案

ilenames = ['cats.txt', 'dogs.txt']

for filename in filenames:
    print("\nReading file: " + filename)
    try:
        with open(filename) as f:
            contents = f.read()
            print(contents)
    except FileNotFoundError:
        print("  Sorry, I can't find that file.")

两个文件都存在时的输出:

Reading file: cats.txt
henry
clarence
mildred

Reading file: dogs.txt
willie
annahootz
summit

移走文件cats.txt后的输出:

Reading file: cats.txt
  Sorry, I can't find that file.

Reading file: dogs.txt
willie
annahootz
summit

3 记住喜欢的数

练习10-11 喜欢的数

编写一个程序,提示用户输入他喜欢的数,并使用json.dump()将这个数存储到文件中。再编写一个程序,从文件中读取这个值,并打印消息“I know your favorite number! It’s _____.”。

练习10-12 记住喜欢的数

将练习10-11中的两个程序合而为一。如果存储了用户喜欢的数,就向用户显示它;否则提示用户输入他喜欢的数并将其存储到文件中。运行这个程序两次,看看它是否像预期的那样工作。

自编程序

import json

filename = 'number.json'
try:
    with open(filename) as f:
        numRead = json.load(f)

except FileNotFoundError:
    num = input("Please input your favorite number: ")
    with open(filename, 'w') as f:
        json.dump(num, f)
    print("Thanks, I'll remember that.")
    
else:
    print("I know your favorite number! It’s " + numRead + " .")

第一次运行的输出如下:

Please input your favorite number: 100
Thanks, I'll remember that.

第二次运行的输出如下:

 know your favorite number! It’s 100 .

练习10-12 记住喜欢的数 参考答案

import json

try:
    with open('favorite_number.json') as f:
        number = json.load(f)
except FileNotFoundError:
    number = input("What's your favorite number? ")
    with open('favorite_number.json', 'w') as f:
        json.dump(number, f)
    print("Thanks, I'll remember that.")
else:
    print("I know your favorite number! It's " + str(number) + ".")
    

第一次运行时的输出:

What's your favorite number? 42
Thanks, I'll remember that.

第二次运行的输出:

I know your favorite number! It's 42.

4 结语

第47篇

过度抵触工作,并不利于个人的长远发展,要接受。

个人水平有限,有问题欢迎各位大神批评指正!

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值