Python从入门到实践第十章10-6~10-10答案

10-6加法运算

try:
	x = input("Give me a number: ")
 	x = int(x)
 	y = input("Give me next number: ")
 	y = int(y)
except ValueError:
 	print("Sorry, I really needed a number.")
else:
	sum = x + y
	print(f"The sum of {x} and {y} is {sum}.")

10-7 加法计算器

print("Enter 'q' to quit.\n")
while True:
	try:
		x = input("\nGive me a number: ")
		if x == 'q':
			break
		x = int(x)
		y = input("Give me next number: ")
		if y == 'q':
			break
		y = int(y)
	except ValueError:
		print("Sorry, I really needed a number.")
 	else:
 		sum = x + y
 		print(f"The sum of {x} and {y} is {sum}."

10-8猫和狗

(cats.txt和dogs.txt凭喜好自行创建)

def open_file(a_name):  
    try:  
        with open(a_name) as animal:  
            a = animal.read()  
    except FileNotFoundError:  
        print('404 not found!')  
    else:  
        print(a.rstrip())  
animals = [ 'cats.txt', 'dogs.txt']  
for b in animals:  
    open_file(b)

10-9静默的猫和狗

def open_file(a_name):  
    try:  
        with open(a_name) as animal:  
            a = animal.read()  
    except FileNotFoundError:  
        print('404 not found!')  
    else:  
        pass # 只要把这里改了就可以静默了  
animals = [ 'cats.txt', 'dogs.txt']  
for b in animals:  
    open_file(b)

10-10常见单词

def count_words(the):
    try:
        with open(the,encoding = 'UTF-8') as t:
            con = t.read()
    except FileNotFoundError:
        print(f"Sorry,I dont find {the}")
    else:
        words = con.split()
        num_words = len(words)
        print(f"The {the} has about {num_words} the.")
        
        
the = 'alice.txt'
#这个文本文件可以更改
count_words(the)
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值