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)