classCityCountryTestCase(unittest.TestCase): deftest_city_country(self): t = city_country('santigo', 'chile') self.assertEqual(t, 'santigo, chile')
unittest.main()
11-2 人口数量 :修改前面的函数,使其包含第三个必不可少的形参 population ,并返回一个格式为 City, Country - population xxx 的字符串,如 Santiago, Chile - population 5000000 。运行 test_cities.py ,确认测试 test_city_country() 未通过。
defdescribe_battery(self): """ 打印一条描述电瓶容量的消息 """ print("This car has a " + str(self.battery_size) + "-kWh battery.")
defget_range(self): """ 打印一条消息,指出电瓶的续航里程 """ if self.battery_size == 70: range = 240 elif self.battery_size == 85: range = 270 message = "This car can go approximately " + str(range) message += " miles on a full charge." print(message)
defupgrade_battery(self): if self.battery_size != 85: self.battery_size = 85
classCar: """ 一次模拟汽车的简单尝试 """
def__init__(self, make, model, year): self.make = make self.model = model self.year = year self.odometer_reading = 0
defread_odometer(self): print("This car has " + str(self.odometer_reading) + " miles on it.")
defupdate_odometer(self, mileage): if mileage >= self.odometer_reading: self.odometer_reading = mileage else: print("You can't roll back an odometer!")
defincrement_odometer(self, miles): self.odometer_reading += miles
from user import User from admin import Privileges, Admin a = Admin('a', 'b') a.show_privileges()
##9-15 Python Module of the Week :要了解 Python 标准库,一个很不错的资源是网站 Python Module of the Week 。请访问 http://pymotw.com/ 并查看其中的目录,在其中找一个你感兴趣的模块进行探索,或阅读模块 collections 和 random 的文档。
1
https://pymotw.com/3/re/index.html
##10-1 Python 学习笔记 :在文本编辑器中新建一个文件,写几句话来总结一下你至此学到的 Python 知识,其中每一行都以 “In Python you can” 打头。将这个文件命名为learning_python.txt ,并将其存储到为完成本章练习而编写的程序所在的目录中。编写一个程序,它读取这个文件,并将你所写的内容打印三次:第一次打印时读取整个文件;第二次打印时遍历文件对象;第三次打印时将各行存储在一个列表中,再在 with 代码块外打印它们。
1 2 3 4 5 6 7 8 9 10 11 12 13 14
file = 'learning_python.txt' with open(file, 'r', encoding='UTF-8') as f: m = f.read() print(m)
with open(file, 'r', encoding='UTF-8') as f: for line in f: print(line)
with open(file, 'r', encoding='UTF-8') as f: ml = f.readlines() for i in ml: print(i)
##10-2 C 语言学习笔记 :可使用方法 replace() 将字符串中的特定单词都替换为另一个单词。
读取你刚创建的文件 learning_python.txt 中的每一行,将其中的 Python 都替换为另一门语言的名称,如 C 。将修改后的各行都打印到屏幕上。
1 2 3 4 5 6
file = 'learning_python.txt' with open(file, 'r', encoding='UTF-8') as f: ml = f.readlines() for i in ml: i = i.replace('Python', 'C') print(i)
a = input('Enter the first number:\n') b = input('Enter the second number:\n') try: print(int(a) + int(b)) except TypeError as e: print("TypeError!\n", e)
##10-7 加法计算器 :将你为完成练习 10-6 而编写的代码放在一个 while 循环中,让用户犯错(输入的是文本而不是数字)后能够继续输入数字。
1 2 3 4 5 6 7
whileTrue: a = input('Enter the first number:\n') b = input('Enter the second number:\n') try: print(int(a) + int(b)) except TypeError as e: print("TypeError!\n", e)
f1 = 'cats.txt ' f2 = 'dogs.txt' try: with open(f1, 'r') as f: print(f.read()) except FileNotFoundError as e: print(e) try: with open(f2, 'r') as f: print(f.read()) except FileNotFoundError as e: print(e)
import json f1 = 'num.json' n = input("Enter a number:\n") with open(f1, 'w') as f: json.dump(n, f) with open(f1) as f: nn = json.load(f) print("I know your favorite number! It's {}.".format(nn))
import json f1 = 'num.json' try: with open(f1) as f: nn = json.load(f) print("I know your favorite number! It's {}.".format(nn)) except FileNotFoundError as e: n = input("Enter a number:\n") with open(f1, 'w') as f: json.dump(n, f)
username = input("What is your name? ") filename = 'username.json' with open(filename, 'w') as f_obj: json.dump(username, f_obj) return username
defgreet_user(): """ 问候用户,并指出其名字 """ a = input("What's your name?\n") if a == get_stored_username(): username = get_stored_username() if username: print("Welcome back, " + username + "!") else: username = get_new_username() print("We'll remember you when you come back, " + username + "!") else: username = get_new_username() if username: print("Welcome back, " + username + "!") else: username = get_new_username() print("We'll remember you when you come back, " + username + "!")
m = input("How old are you?\n") while m != "quit": n = int(m) if n < 3: print("Free.") elif n < 12: print("$10.") else: print("$15.") m = input("How old are you?\n")
7-6 三个出口 :以另一种方式完成练习 7-4 或练习 7-5 ,在程序中采取如下所有做法。
在 while 循环中使用条件测试来结束循环。
使用变量 active 来控制循环结束的时机。
使用 break 语句在用户输入 ‘quit’ 时退出循环。
1 2 3 4 5 6 7 8 9 10
active = input("How old are you?\n") while active != "quit": n = int(active) if n < 3: print("Free.") elif n < 12: print("$10.") else: print("$15.") active = input("How old are you?\n")
##7-8 熟食店 :创建一个名为 sandwich_orders 的列表,在其中包含各种三明治的名字;再创建一个名为 finished_sandwiches 的空列表。遍历列表 sandwich_orders ,对于其中的每种三明治,都打印一条消息,如 I made your tuna sandwich ,并将其移到列表 finished_sandwiches 。所有三明治都制作好后,打印一条消息,将这些三明治列出来。
1 2 3 4 5 6
sandwich_orders = ['1', '2', '3'] finished_sandwiches = [] while len(sandwich_orders) > 0: finished_sandwiches.append(sandwich_orders[0]) print("I made your %s sandwich."%sandwich_orders[0]) del sandwich_orders[0]
sandwich_orders = ['1', '2', '3', 'pastrami', 'pastrami', 'pastrami'] finished_sandwiches = [] print("Pastrami is NOT available.") while'pastrami'in sandwich_orders: sandwich_orders.remove('pastrami') while len(sandwich_orders) > 0: finished_sandwiches.append(sandwich_orders[0]) print("I made your %s sandwich."%sandwich_orders[0]) del sandwich_orders[0]
##7-10 梦想的度假胜地 :编写一个程序,调查用户梦想的度假胜地。使用类似于 “If you could visit one place in the world, where would you go?” 的提示,并编写一个打印调查结果的代码块。
1 2 3 4
m = input("If you could visit one place in the world, where would you go?\n") while m != "quit": print(m) m = input("If you could visit one place in the world, where would you go?\n")
defdisplay_message(): print("I learn function in python.") display_message() display_message()
##8-2 喜欢的图书 :编写一个名为 favorite_book() 的函数,其中包含一个名为 title 的形参。这个函数打印一条消息,如 One of my favorite books is Alice in Wonderland 。调用这个函数,并将一本图书的名称作为实参传递给它。
1 2 3
deffavorite_book(title): print("One of my favorite books is %s."%title) favorite_book('Alice in Wonderland')
##8-3 T 恤 :编写一个名为 make_shirt() 的函数,它接受一个尺码以及要印到 T 恤上的字样。这个函数应打印一个句子,概要地说明 T 恤的尺码和字样。使用位置实参调用这个函数来制作一件 T 恤;再使用关键字实参来调用这个函数。
1 2 3 4
defmake_shirt(size, mes): print("Size is %s, message is %s."%(size, mes)) make_shirt('XL', 'UNDERTALE') make_shirt(size='XL', mes='UNDERTALE')
##8-4 大号 T 恤 :修改函数 make_shirt() ,使其在默认情况下制作一件印有字样 “I love Python” 的大号 T 恤。调用这个函数来制作如下 T 恤:一件印有默认字样的大号 T 恤、一件印有默认字样的中号 T 恤和一件印有其他字样的 T 恤(尺码无关紧要)。
1 2 3 4 5
defmake_shirt(size='XL', mes='I love Python'): print("Size is %s, message is %s."%(size, mes)) make_shirt() make_shirt('L') make_shirt('XL', 'UNDERTALE')
##8-5 城市 :编写一个名为 describe_city() 的函数,它接受一座城市的名字以及该城市所属的国家。这个函数应打印一个简单的句子,如 Reykjavik is in Iceland 。给用于存储国家的形参指定默认值。为三座不同的城市调用这个函数,且其中至少有一座城市不属于默认国家。
1 2 3 4 5
defdescribe_city(name, country='Hyrule'): print("%s is in %s."%(name, country)) describe_city('a') describe_city('b') describe_city('c', 'Wahaha')
defmake_album(name, album, count=''): if count != '': return {name: album, 'count': count} else: return {name: album} for i, j in make_album('a', 'b').items(): print("%s: %s"%(i, j)) for i, j in make_album('a', 'b', '123').items(): print("%s: %s"%(i, j))
##8-8 用户的专辑 :在为完成练习 8-7 编写的程序中,编写一个 while 循环,让用户输入一个专辑的歌手和名称。获取这些信息后,使用它们来调用函数 make_album() ,并将创建的字典打印出来。在这个 while 循环中,务必要提供退出途径。
1 2 3 4 5 6 7 8 9 10 11 12
defmake_album(name, album, count=''): if count != '': return {name: album, 'count': count} else: return {name: album} m = input('Name: ') n = input('Album: ') while m != 'quit'and n != 'quit': for i, j in make_album(m, n).items(): print("%s: %s"%(i, j)) m = input('Name: ') n = input('Album: ')
l = ['1', '2', '3'] defshow_magicians(l): for i in l: print(i) defmake_great(l): i = 0 while i < len(l): l[i] = 'the Great ' + l[i] i += 1 make_great(l) show_magicians(l)
l = ['1', '2', '3'] defshow_magicians(l): for i in l: print(i) defmake_great(l): i = 0 while i < len(l): l[i] = 'the Great ' + l[i] i += 1 return l m = make_great(l[:]) show_magicians(l) show_magicians(m)
defbuild_profile(first, last, **user_info): """创建一个字典,其中包含我们知道的有关用户的一切""" profile = {} profile['first_name'] = first profile['last_name'] = last for key, value in user_info.items(): profile[key] = value return profile user_profile = build_profile('albert', 'einstein', location='princeton', field='physics', sex='male') print(user_profile)
defmake_car(band, size, **info): p = {} p['band'] = band p['size'] = size for i, j in info.items(): p[i] = j return p car = make_car('subaru', 'outback', color='blue', tow_package=True)
defshow_completed_models(completed_models): """ 显示打印好的所有模型 """ print("\nThe following models have been printed:") for completed_model in completed_models: print(completed_model)
# print_models.py from printing_functions import print_models, show_completed_models
alien_color = 'green' if alien_color == 'green': print("You get 5 points.") elif alien_color == 'yellow': print("You get 10 points.") else: print("You get 15 points.") alien_color = 'yellow' if alien_color == 'green': print("You get 5 points.") elif alien_color == 'yellow': print("You get 10 points.") else: print("You get 15 points.") alien_color = 'red' if alien_color == 'green': print("You get 5 points.") elif alien_color == 'yellow': print("You get 10 points.") else: print("You get 15 points.")
5-6 人生的不同阶段 :设置变量 age 的值,再编写一个 if-elif-else 结构,根据 age 的值判断处于人生的哪个阶段。
如果一个人的年龄小于 2 岁,就打印一条消息,指出他是婴儿。
如果一个人的年龄为 2 (含)~ 4 岁,就打印一条消息,指出他正蹒跚学步。
如果一个人的年龄为 4 (含)~ 13 岁,就打印一条消息,指出他是儿童。
如果一个人的年龄为 13 (含)~ 20 岁,就打印一条消息,指出他是青少年。
如果一个人的年龄为 20 (含)~ 65 岁,就打印一条消息,指出他是成年人。
如果一个人的年龄超过 65 (含)岁,就打印一条消息,指出他是老年人。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
deftage(age): if age < 2: print("他是婴儿") elif age < 4: print("他正蹒跚学步") elif age < 13: print("他是儿童") elif age < 20: print("他是青少年") elif age < 65: print("他是成年人") else: print("他是老年人") tage(1) tage(3) tage(12) tage(19) tage(64) tage(65)
5-7 喜欢的水果 :创建一个列表,其中包含你喜欢的水果,再编写一系列独立的 if 语句,检查列表中是否包含特定的水果。
将该列表命名为 favorite_fruits ,并在其中包含三种水果。
编写 5 条 if 语句,每条都检查某种水果是否包含在列表中,如果包含在列表中,就打印一条消息,如 “You really like bananas!” 。
1 2 3 4 5 6 7 8 9
deftf(name): favorite_fruits = ["apple", "banana", "orange"] if name in favorite_fruits: print("You eally like %s!"%name) tf("apple") tf("banana") tf("orange") tf("pear") tf("strawberry")
如果用户名为 ‘admin’ ,就打印一条特殊的问候消息,如 “Hello admin, would you like to see a status report?” 。
否则,打印一条普通的问候消息,如 “Hello Eric, thank you for logging in again” 。
1 2 3 4 5 6
n = ["admin", "Eric", "Link", "Zelda", "Mifa"] for i in n: if i == 'admin': print("Hello admin, would you like to see a status report?") else: print("Hello %s, thank you for logging in again."%i)
5-9 处理没有用户的情形 :在为完成练习 5-8 编写的程序中,添加一条 if 语句,检查用户名列表是否为空。
如果为空,就打印消息 “We need to find some users!” 。
删除列表中的所有用户名,确定将打印正确的消息。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
n = ["admin", "Eric", "Link", "Zelda", "Mifa"] if len(n) == 0: print("We need to find some users!") else: for i in n: if i == 'admin': print("Hello admin, would you like to see a status report?") else: print("Hello %s, thank you for logging in again."%i) n = [] if len(n) == 0: print("We need to find some users!") else: for i in n: if i == 'admin': print("Hello admin, would you like to see a status report?") else: print("Hello %s, thank you for logging in again."%i)
current_users = ["admin", "Eric", "Link", "Zelda", "Mifa"] new_users = ["Admin", "ErIc", "Mario", "Peach", "Komeji Koishi"] for i in new_users: if i.lower() in [j.lower() for j in current_users]: print("Please enter another name.") else: print("This username is not used.")
d = {"integer": "integer", "double": "double precision float point number", "float": "single precision float point number", "function": "a procedure process data", "variable": "a place which can be read and write"} for key, value in d.items(): print("%s\t: %s"%(key, value))
d = {"integer": "integer", "double": "double precision float point number", "float": "single precision float point number", "function": "a procedure process data", "variable": "a place which can be read and write", "bool": "bool", "char": "char", "short": "short integer", "long": "long integer", "long long": "long long integer"} for key, value in d.items(): print("%s\t: %s"%(key, value))
使用循环为每条河流打印一条消息,如 “The Nile runs through Egypt.” 。
使用循环将该字典中每条河流的名字都打印出来。
使用循环将该字典包含的每个国家的名字都打印出来。
1 2 3 4 5
r = {"Nile": "Egypt", "Huang": "China", "Chang": "China"} for key, value in r.items(): print("The %s runs through %s."%(key, value)) print(key) print(value)
p = ['jen', 'sarah', 'edward', 'phil', 'link'] favorite_languages = { 'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python', } for name in p: if name in favorite_languages: print("%s, thank you to attend this survey!"%name) else: print("%s, I want to invite you to do a survey."%name)
##6-7 人 :在为完成练习 6-1 而编写的程序中,再创建两个表示人的字典,然后将这三个字典都存储在一个名为 people 的列表中。遍历这个列表,将其中每个人的所有信息都打印出来。
1 2 3 4 5 6 7 8
l = [ {"first_name": "Riku", "last_name": "Dora", "age": 18, "city": "Unkown"}, {"first_name": "Shuvi", "last_name": "Dora", "age": 18, "city": "Unkown"}, {"first_name": "Steven", "last_name": "Dora", "age": 18, "city": "Unkown"} ] for info in l: for key, value in info.items(): print("%s\t: %s"%(key, value))
favorite_places = { "link": ["p1", "p2", "p3"], "zelda": ["p4", "p5", "p6"], "mifa": ["p7", "p8", "p9"] } for i, j in favorite_places.items(): print("%s : ["%i) for k in j: print("\t%s"%k) print("]")
num = { "Link": [1, 6], "Zelda": [2, 7], "Mifa": [3, 8], "Mario": [4, 9], "Peach": [5, 10] } for key, value in num.items(): print("%s likes ["%key) for i in value: print("\t%d"%i) print("]")
##6-11 城市 :创建一个名为 cities 的字典,其中将三个城市名用作键;对于每座城市,都创建一个字典,并在其中包含该城市所属的国家、人口约数以及一个有关该城市的事实。在表示每座城市的字典中,应包含 country 、 population 和 fact 等键。将每座城市的名字以及有关它们的信息都打印出来。
1 2 3 4 5 6 7 8 9 10
cities = { "name1": {"country": "country1", "population": "123456", "fact": "unkown"}, "name2": {"country": "country2", "population": "234567", "fact": "unkown"}, "name3": {"country": "country3", "population": "345678", "fact": "unkown"} } for i, j in cities.items(): print("%s : {"%i) for k, l in j.items(): print("\t%s : %s"%(k, l)) print("}")
names = ["Link", "Zelda", "Mifa"] mes = "I want to invite" for i in names: mes += " " mes += i mes += " to have a dinner." print(mes) absent = "Mifa" print("However, " + absent + " can't have a dinner with us.") for i in range(len(names)): if names[i] == absent: names[i] = "Zoda" break mes = "I want to invite" for i in names: mes += " " mes += i mes += " to have a dinner." print(mes)
names = ["Link", "Zelda", "Mifa"] mes = "I want to invite" for i in names: mes += " " mes += i mes += " to have a dinner." print(mes) print("I found a bigger table.") names.insert(0, "Mario") names.insert(2, "Pitch") names.append("Satori") mes = "I want to invite" for i in names: mes += " " mes += i mes += " to have a dinner." print(mes)
names = ["Link", "Zelda", "Mifa"] mes = "I want to invite" for i in names: mes += " " mes += i mes += " to have a dinner." print(mes) print("I found a bigger table.") names.insert(0, "Mario") names.insert(2, "Pitch") names.append("Satori") mes = "I want to invite" for i in names: mes += " " mes += i mes += " to have a dinner." print(mes) print("I'm sorry that the table maybe unavailable, so I can only invite two people.") while len(names) > 2: print(names.pop() + ", I'm sorry that I can't invite you to have a dinner.") for i in names: print(i + ", I am so happy that I will have a dinner with you.") del names[0] del names[0] print(names)
names = ["Link", "Zelda", "Mifa"] mes = "I want to invite" for i in names: mes += " " mes += i mes += " to have a dinner." print(mes) print("I have invited " + str(len(names)) + " people to my dinner.")
l = [] for i in range(1, 11): l.append(i**3) for i in l: print(i)
## 4-9 立方解析 :使用列表解析生成一个列表,其中包含前 10 个整数的立方。
1 2
l = [i**3for i in range(1, 11)] print(l)
## 4-10 切片 :选择你在本章编写的一个程序,在末尾添加几行代码,以完成如下任务。
打印消息 “The first three items in the list are:” ,再使用切片来打印列表的前三个元素。
打印消息 “Three items from the middle of the list are:” ,再使用切片来打印列表中间的三个元素。
打印消息 “The last three items in the list are:” ,再使用切片来打印列表末尾的三个元素。
1 2 3 4 5 6 7
l = list(range(1, 11)) print("The first three items in the list are:") print(l[0:3]) print("Three items from the middle of the list are:") print(l[len(l)//2-1:len(l)//2+2]) print("The last three items in the list are:") print(l[-3:-1])
核实你有两个不同的列表。为此,打印消息 “My favorite pizzas are:” ,再使用一个 for 循环来打印第一个列表;打印消息 “My friend’s favorite pizzas are:” ,再使用一个 for 循环来打印第二个列表。核实新增的比萨被添加到了正确的列表中。
1 2 3 4 5 6 7 8 9
p = ["AAA", "BBB", "CCC"] friend_pizzas = p[:] friend_pizzas.append("DDD") print("My favorite pizzas are:") for i in p: print(i) print("My friend's favorite pizzas are:") for i in friend_pizzas: print(i)
## 4-12 使用多个循环 :在本节中,为节省篇幅,程序 foods.py 的每个版本都没有使用 for 循环来打印列表。请选择一个版本的 foods.py ,在其中编写两个 for 循环,将各个食品列表都打印出来。
1 2 3 4 5 6 7 8 9 10
my_foods = ['pizza', 'falafel', 'carrot cake'] friend_foods = my_foods[:] my_foods.append('cannoli') friend_foods.append('ice cream') print("My favorite foods are:") for i in my_foods: print(i) print("\nMy friend's favorite foods are:") for i in friend_pizzas: print(i)
famous_person = "Albert Einstein" message = "A person who never made a mistake never tried anything new." print(famous_person + ' once said, "' + message + '"')
Python 3.5.2 (default, Nov 23 2017, 16:37:01) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import this The Zen of Python, by Tim Peters
Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those!
Welcome to Hexo! This is your very first post. Check documentation for more info. If you get any problems when using Hexo, you can find the answer in troubleshooting or you can ask me on GitHub.