cha10 文件和异常
习题答案
10-1
#-*-coding:gb2312-*-
with open('learning_python.txt') as file_object:
print("第一次打印 读取整个文件")
contents = file_object.read()
print(contents)
#必须要重新读取,不能不读取
with open('learning_python.txt') as file_object:
print("\n第二次打印 遍历文件对象")
for line in file_object:
print(line.rstrip())
with open('learning_python.txt') as file_object:
print("\n第三次打印 隔行储存在列表中,在with代码块外打印")
lines = file_object.readlines()
for line in lines:
print(line.rstrip())
10-2
#-*-coding:gb2312-*-
with open('learning_python.txt') as file_object:
lines = file_object.readlines()
for line in lines:
line = line.replace('Python','C')
print(line.rstrip())
10-3
#-*-coding:gb2312-*-
name = input("Please input your name?\n")
file_name = ('guest_name.txt')
with open(file_name,'w') as file_object:
file_object.write(name)
10-4
file_name = ('guest_book.txt')
with open(file_name,'w') as file_object:
while True:
name = input("Please input your name? Or inpur 'quit' to end.\n")
if name !='quit':
file_object.write(name+"\n")
else:
break
10-5
file_name = ('reason_for_loving_programming.txt')
with open(file_name,'a') as file_object:
while True:
reason = input("Please input reason that make you love programming?\nOr inpur 'no' to end.\n")
if reason !='no':
file_object.write(reason+"\n")
else:
break
10-6
try:
num1 = int(input("Please input a number.\n"))
except ValueError:
print("Sorry. It's not a number.")
else:
try:
num2 = int(input("Please input a number.\n"))
except ValueError:
print("Sorry. It's not a number.")
else:
result = num1 + num2
print("The answer of adding the two number is " + str(result) +".")
10-7 *利用两个While循环
while True :
try:
num1 = int(input("Please input a number.\n"))
except ValueError:
print("Sorry. It's not a number.\n")
continue
else:
break
while True :
try:
num2 = int(input("Please input a number.\n"))
except ValueError:
print("Sorry. It's not a number.\n")
continue
else:
result = num1 + num2
print("The answer of adding the two number is " + str(result) +".")
break
10-8 *
filename_list = ['cats.txt', 'dogs.txt']
for filename in filename_list:
print("File name is "+ filename+".")
try:
with open(filename) as file_object:
contents = file_object.read()
except FileNotFoundError:
print("The file does not exist.\n")
continue
else:
print(contents)
print("\n")
10-9
filename_list = ['cats.txt', 'dogs.txt']
for filename in filename_list:
print("File name is "+ filename+".")
try:
with open(filename) as file_object:
contents = file_object.read()
except FileNotFoundError:
pass #pay attention
continue
else:
print(contents)
print("\n")
10-10
def find_word_times(filename,sp_word):
try:
with open(filename) as file_object:
passage = file_object.read()
except FileNotFoundError:
print(filename.title() + " does not exist.")
else:
print(sp_word +" appears in "+ filename[:-4] + " "
+str(passage.count(sp_word)) + " times.")
find_word_times("the modern traveller.txt",'the')
10-11
import json
filename='number.txt'
num = input("Please input your favorite number.\n")
with open(filename,'w') as f_object:
json.dump(str(num),f_object)
with open(filename) as f_object:
f_num= json.load(f_object)
print("I know your favorite number! It's " + f_num +".")
10-12
import json
filename='favorite_number.txt'
try:
with open(filename) as f_object:
name_num= json.load(f_object)
except FileNotFoundError:
num= input('Please input your favorite number.\n')
with open(filename,'a') as f_object:
json.dump(num,f_object)
else:
with open(filename) as f_object:
print("I Know your favorite number! It's "+ json.load(f_object)+".")
10-13
import json
def get_stored_username():
filename = 'username.json'
try:
with open(filename) as f_obj:
username = json.load(f_obj)
except FileNotFoundError:
return None
else:
return username
def get_new_username():
username =input("What's your name?")
filename = 'username.json'
with open(filename,'a') as f_obj:
json.dump(username,f_obj)
return username
def greet_user():
username = get_stored_username()
if username!=None:
old_user = input("Are you name is " + username + "? Please input y or n.\n")
if old_user =='y':
print('Welcome back, '+username +"!")
else:
username = get_new_username()
print("We'll remember you when you come back " + username +"!\n")
greet_user()
cha11 测试代码
习题答案
11-1
#city_functions.py
def city_country(city_name, country_name):
return city_name.title()+", "+country_name.title()
#test_cities.py
import unittest
from city_functions import city_country
class CityCountryTest(unittest.TestCase):
def test_city_country(self):
cc = city_country('santiago','chile')
self.assertEqual(cc,'Santiago, Chile')
unittest.main()
11-2
#city_functions.py
def city_country(city_name, country_name, population):
return city_name.title()+", "+country_name.title()+" - population " +str(population)
#test_cities.py
import unittest
from city_functions import city_country
class CityCountryTest(unittest.TestCase):
def test_city_country(self):
cc = city_country('santiago','chile', 5000000)
self.assertEqual(cc,'Santiago, Chile - population 5000000')
unittest.main()
population参数可选
#city_functions.py
def city_country(city_name, country_name, population=0):
return city_name.title()+", "+country_name.title()+" - population " +str(population)
#test_cities.py
import unittest
from city_functions import city_country
class CityCountryTest(unittest.TestCase):
def test_city_country(self):
cc = city_country('santiago','chile', 5000000)
self.assertEqual(cc,'Santiago, Chile - population 5000000')
unittest.main()
11-3
import unittest
class Employee():
def __init__(self, name, family_name, salary):
self.name = name
self.family_name = family_name
self.salary = salary
def give_raise(self, num = 5000):
self.salary = self.salary +num
class EmployeeTest(unittest.TestCase):
def setUp(self): #s小写
self.employ = Employee('john','streep',10000)
self.salary = self.employ.salary
def test_give_default_raise(self):
self.employ.give_raise()
self.assertTrue(self.salary + 5000 == self.employ.salary )
def test_give_custom_raise(self):
self.employ.give_raise(1000)
self.assertTrue(self.salary + 1000 == self.employ.salary )
unittest.main()