手写2000行《python从入门到实践》全部语法习题答案 原创

#1-1 python.org :浏览 Python 主页( http://python.org/ ),寻找你感兴趣的主题。你对 Python 越熟悉,这个网站对你来说就越有用。
老实说不怎么看得懂

#1-2 输入错误 :打开你刚创建的文件 hello_world.py ,在代码中添加一个输入错误,再运行这个程序。输入错误会引发错误吗?你能理解显示的错误消息吗?你能添加
#一个不会导致错误的输入错误吗?你凭什么认为它不会导致错误?
print("Hello Python world!")
prinf("error")
1.会引发
2.理解
3.可以
4.我的经验 你的经验 编译器牛逼

#1-3 无穷的技艺 :如果你编程技艺无穷,你打算开发什么样的程序呢?你就要开始学习编程了;如果心中有目标,就能立即将新学到的技能付诸应用;现在正是草拟
#目标的大好时机。将想法记录下来是个不错的习惯,这样每当需要开始新项目时,都可参考它们。现在请花点时间描绘三个你想创建的程序。
1.siri 小冰 小娜 天猫精灵 live2d交互 多合一 (手写女朋友)就是适用于PC加手机端的 个人信息智能管理系统 
2.个人博客移动端
3.论坛移动端


#2-1 简单消息: 将一条消息存储到变量中,再将其打印出来。
message = input("输入任何数据")
print(message)

#2-2 多条简单消息: 将一条消息存储到变量中,将其打印出来;再将变量的值修改为一条新消息,并将其打印出来。
message = input("输入任何")
print(message)
Newmessage = input("再次输入任何")
message = Newmessage
print(message)

#2-3 个性化消息: 将用户的姓名存到一个变量中,并向该用户显示一条消息。显示的消息应非常简单,如 “Hello Eric, would you like to learn some Python today?” 。
name = input("输入姓名")
print("hello",name,"!")

#2-4 调整名字的大小写: 将一个人名存储到一个变量中,再以小写、大写和首字母大写的方式显示这个人名。
name = input("输入姓名")
print(name.upper(),name.lower(),name.title())

#2-5 名言: 找一句你钦佩的名人说的名言,将这个名人的姓名和他的名言打印出来。输出应类似于下面这样(包括引号):
name = "alien"
word = " said 'i see,i konw' "
print(name.title()+word)

#2-6 名言 2 : 重复练习 2-5 ,但将名人的姓名存储在变量 famous_person 中,再创建要显示的消息,并将其存储在变量 message 中,然后打印这条消息。
famous_person = "alien"
message = famous_person.title() +" said 'i see,i konw' "
print(message)

#2-7 剔除人名中的空白: 存储一个人名,并在其开头和末尾都包含一些空白字符。务必至少使用字符组合 "\t" 和 "\n" 各一次。
#打印这个人名,以显示其开头和末尾的空白。然后,分别使用剔除函数 lstrip() 、 rstrip() 和 strip() 对人名进行处理,并将结果打印出来。
name = "alien \t \n"
print(name.lstrip(),name.rstrip(),name.strip())

#2-8 数字 8 : 编写 4 个表达式,它们分别使用加法、减法、乘法和除法运算,但结果都是数字 8 。为使用 print 语句来显示结果,务必将这些表达式用括号括起来
print(5+3)
print(9-1)
print(2**3)
print((int)(16/2))

#2-9 最喜欢的数字: 将你最喜欢的数字存储在一个变量中,再使用这个变量创建一条消息,指出你最喜欢的数字,然后将这条消息打印出来。
Best_Num = 7
print("我喜欢这个数字",Best_Num)

#2-10 添加注释: 选择你编写的两个程序,在每个程序中都至少添加一条注释。如果程序太简单,实在没有什么需要说明的,就在程序文件开头加上你的姓名和当前日
#期,再用一句话阐述程序的功能。
没啥用 当我写过了 

#3-1 姓名: 将一些朋友的姓名存储在一个列表中,并将其命名为 names 。依次访问该列表中的每个元素,从而将每个朋友的姓名都打印出来。
names = ['alien','worli']
for name in names :
    print(name.title())


#3-2 问候语: 继续使用练习 3-1 中的列表,但不打印每个朋友的姓名,而为每人打印一条消息。每条消息都包含相同的问候语,但抬头为相应朋友的姓名。
names = ['alien','worli']
for name in names :
    print("hello",name,'!')

#3-3 自己的列表: 想想你喜欢的通勤方式,如骑摩托车或开汽车,并创建一个包含多种通勤方式的列表。根据该列表打印一系列有关这些通勤方式的宣言,如 “I would
#like to own a Honda motorcycle” 。
tools = ['motorcycle','bike']
for tool in tools :
    print("like to own a "+ tool + '!')

#3-4 嘉宾名单 :如果你可以邀请任何人一起共进晚餐(无论是在世的还是故去的),你会邀请哪些人?请创建一个列表,其中包含至少 3 个你想邀请的人;然后,使用
#这个列表打印消息,邀请这些人来与你共进晚餐。
names = ['alien','linda','mark']
for name in names :
    print("我要邀请 "+ name + '一起来吃饭!')

#3-5 修改嘉宾名单 :你刚得知有位嘉宾无法赴约,因此需要另外邀请一位嘉宾。
#以完成练习 3-4 时编写的程序为基础,在程序末尾添加一条 print 语句,指出哪位嘉宾无法赴约。
#修改嘉宾名单,将无法赴约的嘉宾的姓名替换为新邀请的嘉宾的姓名。
#再次打印一系列消息,向名单中的每位嘉宾发出邀请。
names = ['alien','linda','mark']
for name in names :
    print("我要邀请 "+ name + '一起来吃饭!')
print(names[0]+"来不了!")
names[0] = 'wakaka'
for name in names :
    print("我要邀请 "+ name + '一起来吃饭!')

#3-6 添加嘉宾 :你刚找到了一个更大的餐桌,可容纳更多的嘉宾。请想想你还想邀请哪三位嘉宾。
#以完成练习 3-4 或练习 3-5 时编写的程序为基础,在程序末尾添加一条 print 语句,指出你找到了一个更大的餐桌。
#使用 insert() 将一位新嘉宾添加到名单开头。
#使用 insert() 将另一位新嘉宾添加到名单中间。
#使用 append() 将最后一位新嘉宾添加到名单末尾。
#打印一系列消息,向名单中的每位嘉宾发出邀请。
names = ['alien','linda','mark']
for name in names :
    print("我要邀请 "+ name + '一起来吃饭!')
print(names[0]+"来不了!")
names[0] = 'wakaka'
for name in names :
    print("我要邀请 "+ name + '一起来吃饭!')
print("我找到了个更大的饭桌")
names.insert(0,'ladyzhuazhua')
names.insert(len(names)-1,'acac')
names.append('last')
for name in names :
    print("我要邀请 "+ name + '一起来吃饭!')

#3-7 缩减名单 :你刚得知新购买的餐桌无法及时送达,因此只能邀请两位嘉宾。
#以完成练习 3-6 时编写的程序为基础,在程序末尾添加一行代码,打印一条你只能邀请两位嘉宾共进晚餐的消息。
#使用 pop() 不断地删除名单中的嘉宾,直到只有两位嘉宾为止。每次从名单中弹出一位嘉宾时,都打印一条消息,让该嘉宾知悉你很抱歉,无法邀请他来共进
#晚餐。
#对于余下的两位嘉宾中的每一位,都打印一条消息,指出他依然在受邀人之列。
#使用 del 将最后两位嘉宾从名单中删除,让名单变成空的。打印该名单,核实程序结束时名单确实是空的。
names = ['alien','linda','mark']
for name in names :
    print("我要邀请 "+ name + '一起来吃饭!')
print(names[0]+"来不了!")
names[0] = 'wakaka'
for name in names :
    print("我要邀请 "+ name + '一起来吃饭!')
print("我找到了个更大的饭桌")
names.insert(0,'ladyzhuazhua')
names.insert(len(names)-1,'acac')
names.append('last')
for name in names :
    print("我要邀请 "+ name + '一起来吃饭!')
print("卧槽,我只能邀请两位同学一起吃饭啊!")
for name in names :
    if len(names) == 2 :
        break
    else :
        popped_names = names.pop()
        print("卧槽 我很抱歉 ",popped_names,"下次约!")
for name in names :
    print("嘿",name,"你还在名单上,记得一起哦!")
for i in range(0,2) :
    del names[i]
for name in names :
    print(name)

#3-8 放眼世界 :想出至少 5 个你渴望去旅游的地方。
#将这些地方存储在一个列表中,并确保其中的元素不是按字母顺序排列的。
#按原始排列顺序打印该列表。不要考虑输出是否整洁的问题,只管打印原始 Python 列表。
#使用 sorted() 按字母顺序打印这个列表,同时不要修改它。
#再次打印该列表,核实排列顺序未变。
#使用 sorted() 按与字母顺序相反的顺序打印这个列表,同时不要修改它。
#再次打印该列表,核实排列顺序未变。
#使用 reverse() 修改列表元素的排列顺序。打印该列表,核实排列顺序确实变了。
#使用 reverse() 再次修改列表元素的排列顺序。打印该列表,核实已恢复到原来的排列顺序。
#使用 sort() 修改该列表,使其元素按字母顺序排列。打印该列表,核实排列顺序确实变了。
#使用 sort() 修改该列表,使其元素按与字母顺序相反的顺序排列。打印该列表,核实排列顺序确实变了。
places = ['浪漫的土耳其','东京','巴黎','宇宙','银河']
print(places)
print(sorted(places))
print(places)
print(sorted(places,reverse=True))
print(places)
places.reverse()
print(places)
places.reverse()
print(places)
places.sort()
print(places)
places.sort(reverse = True)
print(places)

#3-9 晚餐嘉宾 :在完成练习 3-4~ 练习 3-7 时编写的程序之一中,使用 len() 打印一条消息,指出你邀请了多少位嘉宾来与你共进晚餐。
names = ['alien','linda','mark']
for name in names :
    print("我要邀请 "+ name + '一起来吃饭!')
print(names[0]+"来不了!")
names[0] = 'wakaka'
for name in names :
    print("我要邀请 "+ name + '一起来吃饭!')
people_num = len(names)
print("一共有",people_num,"个人,过来一起吃饭啊啊!")

#3-10 尝试使用各个函数 :想想可存储到列表中的东西,如山岳、河流、国家、城市、语言或你喜欢的任何东西。编写一个程序,在其中创建一个包含这些元素的列
#表,然后,对于本章介绍的每个函数,都至少使用一次来处理这个列表。
list = ['浪漫的土耳其','东京','巴黎','samsara','石原里美']
list.sort()
print(list)
list.sort(reverse = True)
print(list)
print(sorted(list))
print(sorted(list,reverse = True))
list.reverse()
print(list)
print(len(list))

#4-1 比萨 :想出至少三种你喜欢的比萨,将其名称存储在一个列表中,再使用 for 循环将每种比萨的名称都打印出来。
#修改这个 for 循环,使其打印包含比萨名称的句子,而不仅仅是比萨的名称。对于每种比萨,都显示一行输出,如 “I like pepperoni pizza” 。
#在程序末尾添加一行代码,它不在 for 循环中,指出你有多喜欢比萨。输出应包含针对每种比萨的消息,还有一个总结性句子,如 “I really love pizza!” 。
pizzas = ['bnana','cococola','wakaka']
for pizza in pizzas :
    print(pizza,"“I like pepperoni pizza”")
print(pizzas,"all best ","“I really love pizza!”")

#4-2 动物 :想出至少三种有共同特征的动物,将这些动物的名称存储在一个列表中,再使用 for 循环将每种动物的名称都打印出来。
#修改这个程序,使其针对每种动物都打印一个句子,如 “A dog would make a great pet” 。
#在程序末尾添加一行代码,指出这些动物的共同之处,如打印诸如 “Any of these animals would make a great pet!” 这样的句子。。
animals = ['cat','targer','wakaka']
for animal in animals :
    print("A",animal,"““ would make a great pet ”")
print("Any of these animals would make a great pet!" )

#4-3 数到 20 :使用一个 for 循环打印数字 1~20 (含)。
for value in range(1,21) :
    print(value)

#4-4 一百万 :创建一个列表,其中包含数字 1~1 000 000 ,再使用一个 for 循环将这些数字打印出来(如果输出的时间太长,按 Ctrl + C 停止输出,或关闭输出窗口)。
num = list(range(1,10000001))
print(num)

#4-5 计算 1~1 000 000 的总和 :创建一个列表,其中包含数字 1~1 000 000 ,再使用 min() 和 max() 核实该列表确实是从 1 开始,到 1 000 000 结束的。另外,对这个列表
#调用函数 sum() ,看看 Python 将一百万个数字相加需要多长时间。
numbers = list(range(1,1000001))
print("begin",min(numbers))
print("end",max(numbers))
print("sum",sum(numbers))

#4-6 奇数 :通过给函数 range() 指定第三个参数来创建一个列表,其中包含 1~20 的奇数;再使用一个 for 循环将这些数字都打印出来。
q_numbers = list(range(1,21,2))
print(q_numbers)

#4-7 3 的倍数 :创建一个列表,其中包含 3~30 内能被 3 整除的数字;再使用一个 for 循环将这个列表中的数字都打印出来。
q_numbers = list(range(3,31,3))
for value in q_numbers :
    print(value)

#4-8 立方 :将同一个数字乘三次称为立方。例如,在 Python 中, 2 的立方用 2**3 表示。请创建一个列表,其中包含前 10 个整数(即 1~10 )的立方,再使用一个 for 循
#环将这些立方数都打印出来。
my_list = []
for value in range(1,11) :
    q_number = value ** 3
    my_list.append(q_number)
for my_value in my_list :
    print(my_value)

#4-9 立方解析 :使用列表解析生成一个列表,其中包含前 10 个整数的立方。
list = [value ** 3 for value in range(1,11) ]
print(list)

#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:” ,再使用切片来打印列表末尾的三个元素。
list = [value ** 3 for value in range(1,11) ]
print(list)
print("The first three items in the list are:",list[:3])
print("“Three items from the middle of the list are:",list[3:6])
print("“The last three items in the list are:",list[-3:])

#4-11 你的比萨和我的比萨 :在你为完成练习 4-1 而编写的程序中,创建比萨列表的副本,并将其存储到变量 friend_pizzas 中,再完成如下任务。
#在原来的比萨列表中添加一种比萨。
#在列表 friend_pizzas 中添加另一种比萨。
#核实你有两个不同的列表。为此,打印消息 “My favorite pizzas are:” ,再使用一个 for 循环来打印第一个列表;打印消息 “My friend's favorite pizzas are:” ,再使用一
#个 for 循环来打印第二个列表。核实新增的比萨被添加到了正确的列表中。
pizzas = ['bnana','cococola','wakaka']
for pizza in pizzas :
    print(pizza,"“I like pepperoni pizza”")
print(pizzas,"all best ","“I really love pizza!”")
frined_pizzas = pizzas
frined_pizzas.append('balala')
print(" “My favorite pizzas are:”")
for pizza in pizzas :
    print(pizza)
print("“My friend's favorite pizzas are:”")
for pizza in frined_pizzas :
    print(pizza)

#4-12 使用多个循环 :在本节中,为节省篇幅,程序 foods.py 的每个版本都没有使用 for 循环来打印列表。请选择一个版本的 foods.py ,在其中编写两个 for 循环,将各
#个食品列表都打印出来。
my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods[:]
my_foods.append('cannoli')
friend_foods.append('ice cream')
print("My favorite foods are:")
print(my_foods)
print("\nMy friend's favorite foods are:")
print(friend_foods)
for food in my_foods :
    print(food)
for food in friend_foods:
    print(food)

#4-13 自助餐 :有一家自助式餐馆,只提供五种简单的食品。请想出五种简单的食品,并将其存储在一个元组中。
#使用一个 for 循环将该餐馆提供的五种食品都打印出来。
#尝试修改其中的一个元素,核实 Python 确实会拒绝你这样做。
#餐馆调整了菜单,替换了它提供的其中两种食品。请编写一个这样的代码块:给元组变量赋值,并使用一个 for 循环将新元组的每个元素都打印出来。
foods = ('pizza','bnana','wakaka','旋风无敌草莓圣代','爷爷可高兴的喜之郎')
for food in foods:
    print(food)
#foods[1] = 'blll'
foods = ('newewpizza','bnana','wakaka','旋风无敌草莓圣代','奶奶她也很高兴的喜之郎')
for food in foods:
    print(food)

#5-1 条件测试 :编写一系列条件测试;将每个测试以及你对其结果的预测和实际结果都打印出来。你编写的代码应类似于下面这样:
#详细研究实际结果,直到你明白了它为何为 True 或 False 。
#创建至少 10 个测试,且其中结果分别为 True 和 False 的测试都至少有 5 个。
car = 'subaru'
print("Is car == 'subaru'? I predict True.")
print(car == 'subaru')
print("\nIs car == 'audi'? I predict False.")
print(car == 'audi')
if car == 'subaru':
    print("True")
if car != 'subaru':
    print("Flase")

pizza = 'cool'
if pizza == 'cool':
    print(True)
else :
    print(False)

cat = '噬元兽'
if cat == '噬元兽':
    print(True)
else :
    print(False)

t = 1
if t == 1 :
    print(True)
else :
    print(False)

alien = '外星人'
if alien == '外星人' :
    print(True)
else :
    print(False)

space = '重庆最好的蹦迪九八'
if space == '重庆最好的蹦迪九八':
   print(True)
else :
    print(False)

#5-2 更多的条件测试 :你并非只能创建 10 个测试。如果你想尝试做更多的比较,可再编写一些测试,并将它们加入到 conditional_tests.py 中。对于下面列出的各种测
#试,至少编写一个结果为 True 和 False 的测试。
#检查两个字符串相等和不等。
#使用函数 lower() 的测试。
#检查两个数字相等、不等、大于、小于、大于等于和小于等于。
#使用关键字 and 和 or 的测试。
#测试特定的值是否包含在列表中。
#测试特定的值是否未包含在列表中。

a = ['13213516546','14444866843']
c =['21443514646']
u_a = '14444866843'
u_c = '4567837378'
if a[1].lower() == u_c and u_a in a or u_a not in u_a:
    print(True)
else:
    print(False)

#5-3 外星人颜色 #1 :假设在游戏中刚射杀了一个外星人,请创建一个名为 alien_color 的变量,并将其设置为 'green' 、 'yellow' 或 'red' 。
#编写一条 if 语句,检查外星人是否是绿色的;如果是,就打印一条消息,指出玩家获得了 5 个点。
#编写这个程序的两个版本,在一个版本中上述测试通过了,而在另一个版本中未通过(未通过测试时没有输出)。
alien_color = 'yellow'
if alien_color == 'green':
    print(True)
else:
    print(False)

alien_color = 'green'
if alien_color == 'green':
    print(True)

#5-4 外星人颜色 #2 :像练习 5-3 那样设置外星人的颜色,并编写一个 if-else 结构。
#如果外星人是绿色的,就打印一条消息,指出玩家因射杀该外星人获得了 5 个点。
#如果外星人不是绿色的,就打印一条消息,指出玩家获得了 10 个点。
#编写这个程序的两个版本,在一个版本中执行 if 代码块,而在另一个版本中执行 else 代码块。
alien_color = 'blue'
if alien_color == 'green':
    print('你干掉了他,获得了5个点')
else:
    print('你获得了十个点')

alien_color = 'blue'
if alien_color == 'green':
    print('你干掉了他,获得了5个点')
if alien_color != 'green':
    print('你获得了十个点')
    
#5-5 外星人颜色 #3 :将练习 5-4 中的 if-else 结构改为 if-elif-else 结构。
#如果外星人是绿色的,就打印一条消息,指出玩家获得了 5 个点。
#如果外星人是黄色的,就打印一条消息,指出玩家获得了 10 个点。
#如果外星人是红色的,就打印一条消息,指出玩家获得了 15 个点。
#编写这个程序的三个版本,它们分别在外星人为绿色、黄色和红色时打印一条消息。
alien_color = 'blue'
if alien_color == 'green':
    print('你干掉了他,获得了5个点')
elif alien_color == 'red':
    print('你获得了十个点')
elif alien_color == 'yellow':
    print('你获得了15个点')

#5-6 人生的不同阶段 :设置变量 age 的值,再编写一个 if-elif-else 结构,根据 age 的值判断处于人生的哪个阶段。
#如果一个人的年龄小于 2 岁,就打印一条消息,指出他是婴儿。
#如果一个人的年龄为 2 (含)~ 4 岁,就打印一条消息,指出他正蹒跚学步。
#如果一个人的年龄为 4 (含)~ 13 岁,就打印一条消息,指出他是儿童。
#如果一个人的年龄为 13 (含)~ 20 岁,就打印一条消息,指出他是青少年。
#如果一个人的年龄为 20 (含)~ 65 岁,就打印一条消息,指出他是成年人。
#如果一个人的年龄超过 65 (含)岁,就打印一条消息,指出他是老年人。
age = 155155348
if age < 2:
    print("你就是个婴儿")
elif age >2 and age <4:
    print("你怕不是蹒跚学步")
elif age >4 and age <13:
    print("你就是个儿童")
elif age >13 and age <20:
    print("你就是个青少年")
elif age >20 and age <65:
    print("你就是个成年人")
elif age >65:
    print("你就是个老年人")

#5-7 喜欢的水果 :创建一个列表,其中包含你喜欢的水果,再编写一系列独立的 if 语句,检查列表中是否包含特定的水果。
#将该列表命名为 favorite_fruits ,并在其中包含三种水果。
#编写 5 条 if 语句,每条都检查某种水果是否包含在列表中,如果包含在列表中,就打印一条消息,如 “You really like bananas!” 。
favorite_fruits = ['banana','apple','dokiki','wakaka','balala']
if 'banana' in favorite_fruits:
    print('banana You really like bananas!')
if 'apple' in favorite_fruits:
    print('apple You really like apple!')
if 'wakaka' in favorite_fruits:
    print('wakaka You really like wakaka!')
if 'balala' in favorite_fruits:
    print('balala You really like balala!')
if 'dokiki' in favorite_fruits:
    print('dokiki You really like dokiki!')

#5-8 以特殊方式跟管理员打招呼 :创建一个至少包含 5 个用户名的列表,且其中一个用户名为 'admin' 。想象你要编写代码,在每位用户登录网站后都打印一条问
#候消息。遍历用户名列表,并向每位用户打印一条问候消息。
#如果用户名为 'admin' ,就打印一条特殊的问候消息,如 “Hello admin, would you like to see a status report?” 。
#否则,打印一条普通的问候消息,如 “Hello Eric, thank you for logging in again” 。
names = ['admin','小李','晓红','肖黄','小吕']
for name in names :
    if name == 'admin':
        print( "“Hello admin, would you like to see a status report?")
    else:
        print(name,'hello',"thank you for logging in again")

#5-9 处理没有用户的情形 :在为完成练习 5-8 编写的程序中,添加一条 if 语句,检查用户名列表是否为空。
#如果为空,就打印消息 “We need to find some users!” 。
#删除列表中的所有用户名,确定将打印正确的消息。
names = ['admin','小李','晓红','肖黄','小吕']
for i in range(0,len(names)) :
    names.pop()
if names:
    for name in names :
        if name == 'admin':
            print( "“Hello admin, would you like to see a status report?")
        else:
            print(name,'hello',"thank you for logging in again")
else:
    print("“We need to find some users!")

#5-10 检查用户名 :按下面的说明编写一个程序,模拟网站确保每位用户的用户名都独一无二的方式。
#创建一个至少包含 5 个用户名的列表,并将其命名为 current_users 。
#再创建一个包含 5 个用户名的列表,将其命名为 new_users ,并确保其中有一两个用户名也包含在列表 current_users 中。
#遍历列表 new_users ,对于其中的每个用户名,都检查它是否已被使用。如果是这样,就打印一条消息,指出需要输入别的用户名;否则,打印一条消息,指
#出这个用户名未被使用。
#确保比较时不区分大消息;换句话说,如果用户名 'John' 已被使用,应拒绝用户名 'JOHN' 。
current_users = ['admin','小李','晓红','肖黄','小吕']
new_users = ['admin','小惠','晓红','协和','男科']
for name in new_users :
    if name in current_users:
        print('sorry',name,'you need found an other name !')

#5-11 序数 :序数表示位置,如 1st 和 2nd 。大多数序数都以 th 结尾,只有 1 、 2 和 3 例外。
#在一个列表中存储数字 1~9 。
#遍历这个列表。
#在循环中使用一个 if-elif-else 结构,以打印每个数字对应的序数。输出内容应为 1st 、 2nd 、 3rd 、 4th 、 5th 、 6th 、 7th 、 8th 和 9th ,但每个序
#数都独占一行。
numbers = [number for number in range (1,11)]
for number in numbers:
    if number == 1:
        print("1st")
    elif number == 2:
        print("2rd")
    elif number == 3:
        print("3随便是什么d")
    else:
        print(number,"th")

#5-12 设置 if 语句的格式 :审核你在本章编写的程序,确保正确地设置了条件测试的格式。
 应该是没错

#5-13 自己的想法 :与刚拿起本书时相比,现在你是一名能力更强的程序员了。鉴于你对如何在程序中模拟现实情形有了更深入的认识,你可以考虑使用程序来解决一
#些问题。随着编程技能不断提高,你可能想解决一些问题,请将这方面的想法记录下来。想想你可能想编写的游戏、想研究的数据集以及想创建的 Web 应用程序。
1.siri 小冰 小娜 三个方向三合一的 伪智能机器人
2.个人网站移动端APP
3.游戏啊 就是 就是一那个那样吧 其实 这两个可以合二为一

#6-1 人 :使用一个字典来存储一个熟人的信息,包括名、姓、年龄和居住的城市。该字典应包含键 first_name 、 last_name 、 age 和 city 。将存储在该字典中
#的每项信息都打印出来。
zhengzhi = {
    '姓':"郑",
    "名":"治",
    '年龄':"??",
    "居住的城市":"wakawaka"
    }
print(zhengzhi)

#6-2 喜欢的数字 :使用一个字典来存储一些人喜欢的数字。请想出 5 个人的名字,并将这些名字用作字典中的键;想出每个人喜欢的一个数字,并将这些数字作为值存
#储在字典中。打印每个人的名字和喜欢的数字。为让这个程序更有趣,通过询问朋友确保数据是真实的。
a = {
    'name':'a',
    'num': '1'
    }
b = {
    'name':'b',
    'num': '2'
    }
c = {
    'name':'c',
    'num': '3'
    }
d = {
    'name':'d',
    'num': '4'
    }
e = {
    'name':'e',
    'num': '5'
    }
print(a['name'],a['num'])
print(b['name'],b['num'])
print(c['name'],c['num'])
print(d['name'],d['num'])
print(e['name'],e['num'])

#6-3 词汇表 : Python 字典可用于模拟现实生活中的字典,但为避免混淆,我们将后者称为词汇表。
#想出你在前面学过的 5 个编程词汇,将它们用作词汇表中的键,并将它们的含义作为值存储在词汇表中。
#以整洁的方式打印每个词汇及其含义。为此,你可以先打印词汇,在它后面加上一个冒号,再打印词汇的含义;也可在一行打印词汇,再使用换行符( \n )插
#入一个空行,然后在下一行以缩进的方式打印词汇的含义。
p = {
    'int' : '整型',
    'float':"浮点形",
    'double':"双浮点",
    'string':"字符串",
    'char':"单字符",
    "longlong":"双长"
    }
for v,k in p.items():
    print(v,k)

#6-4 词汇表 2 :既然你知道了如何遍历字典,现在请整理你为完成练习 6-3 而编写的代码,将其中的一系列 print 语句替换为一个遍历字典中的键和值的循环。确定该
#循环正确无误后,再在词汇表中添加 5 个 Python 术语。当你再次运行这个程序时,这些新术语及其含义将自动包含在输出中。
p = {
    'int' : '整型',
    'float':"浮点形",
    'double':"双浮点",
    'string':"字符串",
    'char':"单字符",
    "longlong":"双长",
    'print()':"输出",
    "list":"表格",
    "elif":"除了 如果",
    "字典":"字典就是字典啊",
    "元组":"元组就是元组啊"
    }
for v,k in p.items():
    print(v,k)

#6-5 河流 :创建一个字典,在其中存储三条大河流及其流经的国家。其中一个键 — 值对可能是 'nile': 'egypt' 。
#使用循环为每条河流打印一条消息,如 “The Nile runs through Egypt.” 。
#使用循环将该字典中每条河流的名字都打印出来。
#使用循环将该字典包含的每个国家的名字都打印出来。
rivers = {
    'nile': 'egypt',
    "长江":"china",
    "恒河":"印度",
    "尼罗河":"埃及",
    "巴黎水":"巴黎"
    }
for river,place in rivers.items():
    print("the",river,"runs through ",place)

#6-6 调查 :在 6.3.1 节编写的程序 favorite_languages.py 中执行以下操作。
#创建一个应该会接受调查的人员名单,其中有些人已包含在字典中,而其他人未包含在字典中。
#遍历这个人员名单,对于已参与调查的人,打印一条消息表示感谢。对于还未参与调查的人,打印一条消息邀请他参与调查。
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for name, language in favorite_languages.items():
    print(name.title() + "'s favorite language is " +
    language.title() + ".")
peoples = ['jen','balala','sarah']
for people in peoples:
    print(people,'\n')
    if people in favorite_languages:
        print("thanks")
    else:
        print("invite you to join us")

#6-7 人 :在为完成练习 6-1 而编写的程序中,再创建两个表示人的字典,然后将这三个字典都存储在一个名为 people 的列表中。遍历这个列表,将其中每个人的所有
#信息都打印出来。对于还未参与调查的人,打印一条消息邀请他参与调查。
zhengzhi = {
    '姓':"郑",
    "名":"治",
    '年龄':"??",
    "居住的城市":"wakawaka"
    }
ladyzhuazhua = {
    '姓名':"石原里美",
    '年龄':"18",
    "居住的城市":"日本"
    }
wakawaka = {
    '姓名':"aputon",
    '年龄':"18",
    "居住的城市":"巴黎"
    }
list = []
list.append(zhengzhi)
list.append(ladyzhuazhua)
list.append(wakawaka)
print(list)

#6-8 宠物 :创建多个字典,对于每个字典,都使用一个宠物的名称来给它命名;在每个字典中,包含宠物的类型及其主人的名字。将这些字典存储在一个名为 pets
#的列表中,再遍历该列表,并将宠物的所有信息都打印出来。
popo = {
    "种类":"是一条是狗",
    "主人":"旺旺小码头"
    }
cici = {
    "种类":"是一条是猫猫",
    "主人":"我老婆石原里美"
    }
pets = []
pets.append(popo)
pets.append(cici)
print(pets)

#6-9 喜欢的地方 :创建一个名为 favorite_places 的字典。在这个字典中,将三个人的名字用作键;对于其中的每个人,都存储他喜欢的 1~3 个地方。为让这个练
#习更有趣些,可让一些朋友指出他们喜欢的几个地方。遍历这个字典,并将其中每个人的名字及其喜欢的地方打印出来。
favorite_places = {
    "十元里美":["东京",'中国'],
    "wakaka":["扶轮利达",'塞卡',"瓦克"],
    "安提歌哥哥":["巴达罗",'东和'],
    }
for name,place in favorite_places.items():
    print(name,place)

#6-10 喜欢的数字 :修改为完成练习 6-2 而编写的程序,让每个人都可以有多个喜欢的数字,然后将每个人的名字及其喜欢的数字打印出来。
a = {
    'name':'a',
    'num':['41','546','486406']
    }
b = {
    'name':'b',
    'num': ['535','464']
    }
c = {
    'name':'c',
    'num': ['35453','468464']
    }
d = {
    'name':'d',
    'num': ['4546']
    }
e = {
    'name':'e',
    'num': ['64684','534654']
    }
print(a['name'],a['num'])
print(b['name'],b['num'])
print(c['name'],c['num'])
print(d['name'],d['num'])
print(e['name'],e['num'])

#6-11 城市 :创建一个名为 cities 的字典,其中将三个城市名用作键;对于每座城市,都创建一个字典,并在其中包含该城市所属的国家、人口约数以及一个有关该
#城市的事实。在表示每座城市的字典中,应包含 country 、 population 和 fact 等键。将每座城市的名字以及有关它们的信息都打印出来。
cities = {
    "浪漫的土耳其":{
        "国家":"tuerqi",
        "人口约数":"1000000",
        "事实":"浪漫的"
        },
    "东京":{
        "国家":"日本",
        "人口约数":"1000000",
        "事实":"樱花秒速五厘米"
        },
    "巴黎":{
        "国家":"法国",
        "人口约数":"1000000",
        "事实":"巴黎水真的喝不来"
        }
    }
print(cities)

#6-12 扩展 :本章的示例足够复杂,可以以很多方式进行扩展了。请对本章的一个示例进行扩展:添加键和值、调整程序要解决的问题或改进输出的格式。
cities = {
    "浪漫的土耳其":{
        "国家":"tuerqi",
        "人口约数":"1000000",
        "事实":"浪漫的"
        },
    "东京":{
        "国家":"日本",
        "人口约数":"1000000",
        "事实":"樱花秒速五厘米"
        },
    "巴黎":{
        "国家":"法国",
        "人口约数":"1000000",
        "事实":"巴黎水真的喝不来"
        }
    }
for citie,info in cities.items() :
    long_p = info[" 国家 "]+info["人口约数"]+info["事实"]
    print(citie + long_p)

#7-1 汽车租赁 :编写一个程序,询问用户要租赁什么样的汽车,并打印一条消息,如 “Let me see if I can find you a Subaru” 。
car = input("你要租一个什么样的车车?")
print("Let me see if I can find you a ",car)

#7-2 餐馆订位 :编写一个程序,询问用户有多少人用餐。如果超过 8 人,就打印一条消息,指出没有空桌;否则指出有空桌。
num  = int(input("有多少个人吃饭啊?"))
if num >8 :
    print("摸得位子得")
else:
    print("请请请")

#7-3 10 的整数倍 :让用户输入一个数字,并指出这个数字是否是 10 的整数倍。
num = input("随便输入一个数字,我会指出是不是 10 的倍数")
num = int(num)
if num % 10 == 0:
    print(True)
else:
    print(False)

#7-4 比萨配料 :编写一个循环,提示用户输入一系列的比萨配料,并在用户输入 'quit' 时结束循环。每当用户输入一种配料后,都打印一条消息,说我们会在比萨
#中添加这种配料。
pizza = []
while True:
    new = input("输入一个配料")
    if new == 'quit':
        break;
    else:
        pizza.append(new)
        print("我们会添加",new,"这种配料")
   
#7-5 电影票 :有家电影院根据观众的年龄收取不同的票价:不到 3 岁的观众免费; 3~12 岁的观众为 10 美元;超过 12 岁的观众为 15 美元。请编写一个循环,在其中询问用
#户的年龄,并指出其票价。
age = input("你多少岁了?")
age = int(age)
if age <3 :
    print("免费哦")
elif age>3 and age<12:
    print("收你10美元")
else:
    print("收你15元")

#7-6 三个出口 :以另一种方式完成练习 7-4 或练习 7-5 ,在程序中采取如下所有做法。
#在 while 循环中使用条件测试来结束循环。
#使用变量 active 来控制循环结束的时机。
#使用 break 语句在用户输入 'quit' 时退出循环。
pizza = []
active = False
while True:
    new = input("输入一个配料")
    if new == 'quit':
        active = True
    if active:
        break;
    else:
        pizza.append(new)
        print("我们会添加",new,"这种配料")

#7-7 无限循环 :编写一个没完没了的循环,并运行它(要结束该循环,可按 Ctrl +C ,也可关闭显示输出的窗口)。
while 1 :
    print("COOL_Z")

#7-8 熟食店 :创建一个名为 sandwich_orders 的列表,在其中包含各种三明治的名字;再创建一个名为 finished_sandwiches 的空列表。遍历列
#表 sandwich_orders ,对于其中的每种三明治,都打印一条消息,如 I made your tuna sandwich ,并将其移到列表 finished_sandwiches 。所有三明
#治都制作好后,打印一条消息,将这些三明治列出来。
sandwich_orders = ['balala','wakaka','blili']
finished_sandwiches = []
for order in sandwich_orders:
    print("I made your", order," sandwich ")
    finished_sandwiches.append(order)
for order in sandwich_orders:
    print(order)
for order in finished_sandwiches:
    print(order)

#7-9 五香烟熏牛肉( pastrami )卖完了 :使用为完成练习 7-8 而创建的列表 sandwich_orders ,并确保 'pastrami' 在其中至少出现了三次。在程序开头附近添加
#这样的代码:打印一条消息,指出熟食店的五香烟熏牛肉卖完了;再使用一个 while 循环将列表 sandwich_orders 中的 'pastrami' 都删除。确认最终的列
#表 finished_sandwiches 中不包含 'pastrami' 。
sandwich_orders = ['balala','wakaka','blili','pastrami' ,'pastrami' ,'pastrami' ]
print("熟食店的五香烟熏牛肉卖完了")
while 'pastrami' in sandwich_orders:
     sandwich_orders.remove('pastrami')
if 'pastrami' not in sandwich_orders:
   print( 'pastrami' ,"没在里面啊")

#7-10 梦想的度假胜地 :编写一个程序,调查用户梦想的度假胜地。使用类似于 “If you could visit one place in the world, where would you go?” 的提示,并编写一个打印调查
#结果的代码块。
places = []
while 1:
        place = input("“If you could visit one place in the world, where would you go?” ")
        if place == 'quit':
            break
        else :
            places.append(place)
            continue
print(places)

#8-1 消息 :编写一个名为 display_message() 的函数,它打印一个句子,指出你在本章学的是什么。调用这个函数,确认显示的消息正确无误。
def display_message():
    print("学自定义函数哦!")
display_message()

#8-2 喜欢的图书 :编写一个名为 favorite_book() 的函数,其中包含一个名为 title 的形参。这个函数打印一条消息,如 One of my favorite books is
#Alice in Wonderland 。调用这个函数,并将一本图书的名称作为实参传递给它。
def  favorite_book(title):
    print("One of my favorite books is",title)
favorite_book("threekindom")

#8-3 T 恤 :编写一个名为 make_shirt() 的函数,它接受一个尺码以及要印到 T 恤上的字样。这个函数应打印一个句子,概要地说明 T 恤的尺码和字样。
#使用位置实参调用这个函数来制作一件 T 恤;再使用关键字实参来调用这个函数。
def make_shirt():
    size = input("你要的尺码")
    word = input("你要印刷的字样")
    print("这件衣服大",size,"字样",word)
make_shirt()

#8-4 大号 T 恤 :修改函数 make_shirt() ,使其在默认情况下制作一件印有字样 “I love Python” 的大号 T 恤。调用这个函数来制作如下 T 恤:一件印有默认字样的大号 T
#恤、一件印有默认字样的中号 T 恤和一件印有其他字样的 T 恤(尺码无关紧要)。
def make_shirt(size='XXL',word='I love Python'):
    print("这件衣服大",size,"字样",word)
make_shirt()
make_shirt(word = 'wakka')

#8-5 城市 :编写一个名为 describe_city() 的函数,它接受一座城市的名字以及该城市所属的国家。这个函数应打印一个简单的句子,如 Reykjavik is in
#Iceland 。给用于存储国家的形参指定默认值。为三座不同的城市调用这个函数,且其中至少有一座城市不属于默认国家。
def describe_city(place = '天上人间',contry = '华夏'):
    print(place," is in",contry)
describe_city()
describe_city(place = 'wakaka')
describe_city(contry = "wanck")

#8-6 城市名 :编写一个名为 city_country() 的函数,它接受城市的名称及其所属的国家。这个函数应返回一个格式类似于下面这样的字符串:
def city_country(city,country):
    new_p = city +country
    return new_p
q = []
q.append(city_country('adcv ',' asbf'))
q.append(city_country('ababfr ',' crgq e'))
q.append(city_country('cwhve ',' c35v4'))
for k in q :
    print(k)

#8-7 专辑 :编写一个名为 make_album() 的函数,它创建一个描述音乐专辑的字典。这个函数应接受歌手的名字和专辑名,并返回一个包含这两项信息的字典。使
#用这个函数创建三个表示不同专辑的字典,并打印每个返回的值,以核实字典正确地存储了专辑的信息。
def make_album(sigger,album):
    q = sigger + album
    return  q
p =[]
p.append(make_album("v","QEGR"))
p.append(make_album("T"," QRG"))
p.append(make_album("G","WTXWGR"))
print(p)

#8-8 用户的专辑 :在为完成练习 8-7 编写的程序中,编写一个 while 循环,让用户输入一个专辑的歌手和名称。获取这些信息后,使用它们来调用函
#数 make_album() ,并将创建的字典打印出来。在这个 while 循环中,务必要提供退出途径。
def make_album(sigger,album):
    q = sigger +" "+ album
    return  q
p =[]
while 1:
    new_sigger = input("输入歌手")
    new_album = input("输入专辑")
    if new_sigger == 'q' or new_album == 'q':
        break
    else:
        p.append(make_album(new_sigger,new_album))
print(p)

#8-10 了不起的魔术师 :在你为完成练习 8-9 而编写的程序中,编写一个名为 make_great()
#的函数,对魔术师列表进行修改,在每个魔术师的名字中都加入字样 “the
#Great” 。调用函数 show_magicians() ,确认魔术师列表确实变了。
list = ["大卫","刘谦","哈利波特"]
def make_great():
    list[0] = "the greet 大卫"
    list[1] = "the greet刘谦"
    list[2] = "the greet哈利波特"
def  show_magicians(name):
    print("现在让我们欢迎宇宙无敌可亲可爱天下第一的",name)
make_great()
show_magicians(list)

#8-10 了不起的魔术师 :在你为完成练习 8-9 而编写的程序中,编写一个名为 make_great()
#的函数,对魔术师列表进行修改,在每个魔术师的名字中都加入字样 “the
#Great” 。调用函数 show_magicians() ,确认魔术师列表确实变了。
list = ["大卫","刘谦","哈利波特"]
def make_great(list):
    global new_list 
    new_list = []
    for name in list:
        new_list.append("the great"+name)
def  show_magicians(name):
    print("现在让我们欢迎宇宙无敌可亲可爱天下第一的",name)
make_great(list)
show_magicians(new_list)

#8-11 不变的魔术师 :修改你为完成练习 8-10 而编写的程序,在调用函数 make_great() 时,向它传递魔术师列表的副本。由于不想修改原始列表,请返回修改后的
#列表,并将其存储到另一个列表中。分别使用这两个列表来调用 show_magicians() ,确认一个列表包含的是原来的魔术师名字,而另一个列表包含的是添加了字
#样 “the Great” 的魔术师名字。
list = ["大卫","刘谦","哈利波特"]
def make_great(list):
    global new_list 
    new_list = []
    for name in list:
        new_list.append("the great"+name)
def  show_magicians(name):
    print("现在让我们欢迎宇宙无敌可亲可爱天下第一的",name)
make_great(list)
show_magicians(list)
show_magicians(new_list)

#8-12 三明治 :编写一个函数,它接受顾客要在三明治中添加的一系列食材。这个函数只有一个形参(它收集函数调用中提供的所有食材),并打印一条消息,对顾客
#点的三明治进行概述。调用这个函数三次,每次都提供不同数量的实参。
def diy_sand (*any):
    print("你想吃的三明治包含以下素材",any)
diy_sand("蒸熊掌","鱼子酱")
diy_sand("鹿肉")
diy_sand("小鸟酱")

#8-13 用户简介 :复制前面的程序 user_profile.py ,在其中调用 build_profile() 来创建有关你的简介;调用这个函数时,指定你的名和姓,以及三个描述你的键 - 值
#对。
def build_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('郑', '治',
location='重庆',
field='计算机',
something="单身二十年"
)
print(user_profile)

#8-14 汽车 :编写一个函数,将一辆汽车的信息存储在一个字典中。这个函数总是接受制造商和型号,还接受任意数量的关键字实参。这样调用这个函数:提供必不可
#少的信息,以及两个名称 — 值对,如颜色和选装配件。这个函数必须能够像下面这样进行调用:
def make_car (model,manu,**info):
    file = {}
    file['model'] = model 
    file['manu'] = manu
    for key,value in info.items():
        file[key] = value
    return file
car = make_car('subaru', 'outback', color='blue', tow_package=True)
print(car)

#8-15 打印模型 :将示例 print_models.py 中的函数放在另一个名为 printing_functions.py 的文件中;在 print_models.py 的开头编写一条 import 语句,并修改这个文件以使用导
#入的函数。
printing_functions.py
# 首先创建一个列表,其中包含一些要打印的设计
unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']
completed_models = []
# 模拟打印每个设计,直到没有未打印的设计为止
# 打印每个设计后,都将其移到列表 completed_models 中
while unprinted_designs:
    current_design = unprinted_designs.pop()
# 模拟根据设计制作 3D 打印模型的过程
    print("Printing model: " + current_design)
    completed_models.append(current_design)
# 显示打印好的所有模型
print("\nThe following models have been printed:")
for completed_model in completed_models:
    print(completed_model)

 print_models.py
import printing_functions as p
p

#8-16 导入 :选择一个你编写的且只包含一个函数的程序,并将这个函数放在另一个文件中。在主程序文件中,使用下述各种方法导入这个函数,再调用它:
printing_functions.py
def do ():
    unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']
    completed_models = []
    while unprinted_designs:
        current_design = unprinted_designs.pop()
        print("Printing model: " + current_design)
        completed_models.append(current_design)
    print("\nThe following models have been printed:")
    for completed_model in completed_models:
        print(completed_model)

main.py
import printing_functions as p
from printing_functions import do
from printing_functions import do as fn
import printing_functions as mn
from printing_functions import *
p
do()
fn()
mn
do()

#8-17 函数编写指南 :选择你在本章中编写的三个程序,确保它们遵循了本节介绍的函数编写指南。
双峰命名法 缩进 空格 还是 认真的时候有好好注意的

#9-1 餐馆 :创建一个名为 Restaurant 的类,其方法 __init__() 设置两个属性: restaurant_name 和 cuisine_type 。创建一个名
#为 describe_restaurant() 的方法和一个名为 open_restaurant() 的方法,其中前者打印前述两项信息,而后者打印一条消息,指出餐馆正在营业。
class Restaurant():
    def __init__(self,restaurant_name,cuisine_type):
        self.restaurant_name = restaurant_name
        self.cuisine_type = cuisine_type
    def describe_restaurant(self):
        print(self.restaurant_name,self.cuisine_type)
    def open_restaurant(self):
        print(self.restaurant_name,"正在营业")
a_restaurant = Restaurant("蟹堡黄","汉堡包包店")
a_restaurant.open_restaurant()
a_restaurant.describe_restaurant()

#9-2 三家餐馆 :根据你为完成练习 9-1 而编写的类创建三个实例,并对每个实例调用方法 describe_restaurant() 。
class Restaurant():
    def __init__(self,restaurant_name,cuisine_type):
        self.restaurant_name = restaurant_name
        self.cuisine_type = cuisine_type
    def describe_restaurant(self):
        print(self.restaurant_name,self.cuisine_type)
    def open_restaurant(self):
        print(self.restaurant_name,"正在营业")
a_restaurant = Restaurant("蟹堡黄","汉堡包包店")
b_restaurant = Restaurant("早餐中国加盟商","西餐厅")
c_restaurant = Restaurant("正宗法式早茶店","居酒屋")
a_restaurant.describe_restaurant()
b_restaurant.describe_restaurant()
c_restaurant.describe_restaurant()

#9-3 用户 :创建一个名为 User 的类,其中包含属性 first_name 和 last_name ,还有用户简介通常会存储的其他几个属性。在类
#User 中定义一个名
#为 describe_user() 的方法,它打印用户信息摘要;再定义一个名为 greet_user() 的方法,它向用户发出个性化的问候。
#创建多个表示不同用户的实例,并对每个实例都调用上述两个方法。
class uers():
    def __init__(self, first_name, last_name,descireb,number):
        self. first_name = first_name
        self. last_name = last_name
        self. descireb = descireb
        self. number = number 
    def describe_user(self):
        print(self.first_name + self.last_name,self.descireb,self.number)
    def greet_user(self):
        print('hello',self.first_name + self.last_name)
a = uers("黄","蛤","风干镇","100210")
b = uers("何","丽丽","很热镇","468464")
c = uers("堡","嘁嘁嘁","姜山","195210")
a.greet_user()
a.describe_user()
b.greet_user()
b.describe_user()
c.greet_user()
c.describe_user()

#9-4 就餐人数 :在为完成练习 9-1 而编写的程序中,添加一个名为 number_served 的属性,并将其默认值设置为 0 。根据这个类创建一个名为 restaurant 的实
#例;打印有多少人在这家餐馆就餐过,然后修改这个值并再次打印它。
#添加一个名为 set_number_served() 的方法,它让你能够设置就餐人数。调用这个方法并向它传递一个值,然后再次打印这个值。
#添加一个名为 increment_number_served() 的方法,它让你能够将就餐人数递增。调用这个方法并向它传递一个这样的值:你认为这家餐馆每天可能接待的就
#餐人数。
class Restaurant():
    def __init__(self,restaurant_name,cuisine_type):
        self.restaurant_name = restaurant_name
        self.cuisine_type = cuisine_type
    def describe_restaurant(self):
        print(self.restaurant_name,self.cuisine_type)
    def open_restaurant(self):
        print(self.restaurant_name,"正在营业")
    def set_number_severed (self,num):
        print("只接待",num,"个人")
    def increment_number_served(self,num):
        print("我觉得这么牛逼的餐厅每天起码得接待",num,"个人")

a_restaurant = Restaurant("蟹堡黄","汉堡包包店")
a_restaurant.open_restaurant()
a_restaurant.describe_restaurant()
a_restaurant.set_number_severed(10)
a_restaurant.increment_number_served(90)

#9-5 尝试登录次数 :在为完成练习 9-3 而编写的 User 类中,添加一个名为 login_attempts 的属性。编写一个名为
#increment_login_attempts() 的方法,
#它将属性 login_attempts 的值加 1 。再编写一个名为 reset_login_attempts() 的方法,它将属性
#login_attempts 的值重置为 0 。
#根据 User 类创建一个实例,再调用方法 increment_login_attempts() 多次。打印属性 login_attempts
#的值,确认它被正确地递增;然后,调用方
#法 reset_login_attempts() ,并再次打印属性 login_attempts 的值,确认它被重置为 0 。
class uers():
    def __init__(self, first_name, last_name,descireb,number, login_attempts):
        self. first_name = first_name
        self. last_name = last_name
        self. descireb = descireb
        self. number = number 
        self. login_attempts = login_attempts
    def describe_user(self):
        print(self.first_name + self.last_name,self.descireb,self.number)
    def greet_user(self):
        print('hello',self.first_name + self.last_name)
    def increment_login_attempts(self):
        self.login_attempts += 1
    def reset_login_attempts(self):
        self. login_attempts = 0
a = uers("黄","蛤","风干镇","100210",0)
a.increment_login_attempts()
a.increment_login_attempts()
a.increment_login_attempts()
print(a.login_attempts)
a.reset_login_attempts()
print(a.login_attempts)

#9-6 冰淇淋小店 :冰淇淋小店是一种特殊的餐馆。编写一个名为 IceCreamStand 的类,让它继承你为完成练习 9-1 或练习 9-4 而编写的 Restaurant 类。这两个版
#本的 Restaurant 类都可以,挑选你更喜欢的那个即可。添加一个名为 flavors 的属性,用于存储一个由各种口味的冰淇淋组成的列表。编写一个显示这些冰淇淋
#的方法。创建一个 IceCreamStand 实例,并调用这个方法。
class Restaurant():
    def __init__(self,restaurant_name,cuisine_type):
        self.restaurant_name = restaurant_name
        self.cuisine_type = cuisine_type
    def describe_restaurant(self):
        print(self.restaurant_name,self.cuisine_type)
    def open_restaurant(self):
        print(self.restaurant_name,"正在营业")
    def set_number_severed (self,num):
        print("只接待",num,"个人")
    def increment_number_served(self,num):
        print("我觉得这么牛逼的餐厅每天起码得接待",num,"个人")


class IceCreamStand (Restaurant) :
    def __init__(self,restaurant_name,cuisine_type):
        super().__init__(restaurant_name,cuisine_type)
        self. flavors = []
    def display_flavors(self):
        print(self.flavors)


p = IceCreamStand("啊根大肆","流行冰淇淋")
p.flavors.append("香草")
p.flavors.append("菊花")
p.flavors.append("溜溜")
p.display_flavors()

#9-7 管理员 :管理员是一种特殊的用户。编写一个名为 Admin 的类,让它继承你为完成练习 9-3 或练习 9-5 而编写的 User 类。添加一个名为 privileges 的属性,用
#于存储一个由字符串(如 "can add post" 、 "can delete post" 、 "can ban user" 等)组成的列表。编写一个名为 show_privileges() 的方法,它
#显示管理员的权限。创建一个 Admin 实例,并调用这个方法。
class uers():
    def __init__(self, first_name, last_name,descireb,number, login_attempts):
        self. first_name = first_name
        self. last_name = last_name
        self. descireb = descireb
        self. number = number 
        self. login_attempts = login_attempts
    def describe_user(self):
        print(self.first_name + self.last_name,self.descireb,self.number)
    def greet_user(self):
        print('hello',self.first_name + self.last_name)
    def increment_login_attempts(self):
        self.login_attempts += 1
    def reset_login_attempts(self):
        self. login_attempts = 0


class Admin(uers):
    def __init__(self,first_name, last_name,descireb,number, login_attempts):
        super().__init__(first_name, last_name,descireb,number, login_attempts)
        self. privileges = []
    def show_privileges(self):
        print(self.privileges)


Z = Admin("郑","治","重庆","18105756",0)
Z.privileges.append("can add post")
Z.privileges.append("can delete post")
Z.privileges.append("can ban user")
Z.show_privileges()


#9-8 权限 :编写一个名为 Privileges 的类,它只有一个属性 —— privileges ,其中存储了练习 9-7 所说的字符串列表。将方法
#show_privileges() 移到这
#个类中。在 Admin 类中,将一个 Privileges 实例用作其属性。创建一个 Admin 实例,并使用方法 show_privileges()
#来显示其权限。
class uers():
    def __init__(self, first_name, last_name,descireb,number, login_attempts):
        self. first_name = first_name
        self. last_name = last_name
        self. descireb = descireb
        self. number = number 
        self. login_attempts = login_attempts
    def describe_user(self):
        print(self.first_name + self.last_name,self.descireb,self.number)
    def greet_user(self):
        print('hello',self.first_name + self.last_name)
    def increment_login_attempts(self):
        self.login_attempts += 1
    def reset_login_attempts(self):
        self. login_attempts = 0

class  Privileges():
    def __init__(self,privileges = ["can add post","can delete post","can ban user"]):
        self.privileges = privileges
    def show_privileges(self):
        print(self.privileges)    

class Admin(uers):
    def __init__(self,first_name, last_name,descireb,number, login_attempts):
        super().__init__(first_name, last_name,descireb,number, login_attempts)
        self. privileges = []
        self.display = Privileges()

Z = Admin("郑","治","重庆","18105756",0)
Z.display.show_privileges()


#9-9 电瓶升级 :在本节最后一个 electric_car.py 版本中,给 Battery 类添加一个名为 upgrade_battery() 的方法。这个方法检查电瓶容量,如果它不是 85 ,就将它
#设置为 85 。创建一辆电瓶容量为默认值的电动汽车,调用方法 get_range() ,然后对电瓶进行升级,并再次调用 get_range() 。你会看到这辆汽车的续航里程增
#加了。
class Car():
    """ 一次模拟汽车的简单尝试 """
    def __init__(self, make, model, year):
        self.make = make
        self.model = model
        self.year = year
        self.odometer_reading = 0
    def get_descriptive_name(self):
        long_name = str(self.year) + ' ' + self.make + ' ' + self.model
        return long_name.title()
    def read_odometer(self):
        print("This car has " + str(self.odometer_reading) + " miles on it.")
        def update_odometer(self, mileage):
            if mileage >= self.odometer_reading:
                self.odometer_reading = mileage
            else:
                print("You can't roll back an odometer!")
    def increment_odometer(self, miles):
        self.odometer_reading += miles
class ElectricCar(Car):
    """ 电动汽车的独特之处 """
    def __init__(self, make, model, year):
   # 初始化父类的属性 """
      super().__init__(make, model, year)


class Battery():
# 一次模拟电动汽车电瓶的简单尝试 """
    def __init__(self, battery_size=70):
# 初始化电瓶的属性 """
        self.battery_size = battery_size
    def describe_battery(self):
# 打印一条描述电瓶容量的消息 """
        print("This car has a " + str(self.battery_size) + "-kWh battery.")
    def get_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)
    def upgrade_battery(self):
        if self.battery_size != 85:
            self.battery_size = 85


class ElectricCar(Car):
    # 电动汽车的独特之处 """
    def __init__(self, make, model, year):
    #初始化父类的属性,再初始化电动汽车特有的属性
        super().__init__(make, model, year)
        self.battery = Battery()


super_moto = ElectricCar("中央之国","云鲸","2020")
super_moto.battery.get_range()
super_moto.battery.upgrade_battery()
super_moto.battery.get_range()


#9-10 导入 Restaurant 类 :将最新的 Restaurant 类存储在一个模块中。在另一个文件中,导入 Restaurant 类,创建一个 Restaurant 实例,并调
#用 Restaurant 的一个方法,以确认 import 语句正确无误。
Restaurant.py

class Restaurant():
    def __init__(self,restaurant_name,cuisine_type):
        self.restaurant_name = restaurant_name
        self.cuisine_type = cuisine_type
    def describe_restaurant(self):
        print(self.restaurant_name,self.cuisine_type)
    def open_restaurant(self):
        print(self.restaurant_name,"正在营业")

main.py
from Restaurant import *
my_Restaurant =Restaurant("咬金","风味中餐厅")
my_Restaurant.open_restaurant()

#9-11 导入 Admin 类 :以为完成练习 9-8 而做的工作为基础,将 User 、 Privileges 和 Admin
#类存储在一个模块中,再创建一个文件,在其中创建一个 Admin 实例
#并对其调用方法 show_privileges() ,以确认一切都能正确地运行。
web.py

class uers():
    def __init__(self, first_name, last_name,descireb,number, login_attempts):
        self. first_name = first_name
        self. last_name = last_name
        self. descireb = descireb
        self. number = number 
        self. login_attempts = login_attempts
    def describe_user(self):
        print(self.first_name + self.last_name,self.descireb,self.number)
    def greet_user(self):
        print('hello',self.first_name + self.last_name)
    def increment_login_attempts(self):
        self.login_attempts += 1
    def reset_login_attempts(self):
        self. login_attempts = 0

class  Privileges():
    def __init__(self,privileges = ["can add post","can delete post","can ban user"]):
        self.privileges = privileges
    def show_privileges(self):
        print(self.privileges)    

main.py

class Admin(uers):
    def __init__(self,first_name, last_name,descireb,number, login_attempts):
        super().__init__(first_name, last_name,descireb,number, login_attempts)
        self. privileges = []
        self.display = Privileges()
from web import *
z = Admin("郑","治","重庆","18105756",0)
z. display.show_privileges()

#9-12 多个模块 :将 User 类存储在一个模块中,并将 Privileges 和 Admin 类存储在另一个模块中。再创建一个文件,在其中创建一个 Admin 实例,并对其调用方
#法 show_privileges() ,以确认一切都依然能够正确地运行。

web_users.py

class uers():
    def __init__(self, first_name, last_name,descireb,number, login_attempts):
        self. first_name = first_name
        self. last_name = last_name
        self. descireb = descireb
        self. number = number 
        self. login_attempts = login_attempts
    def describe_user(self):
        print(self.first_name + self.last_name,self.descireb,self.number)
    def greet_user(self):
        print('hello',self.first_name + self.last_name)
    def increment_login_attempts(self):
        self.login_attempts += 1
    def reset_login_attempts(self):
        self. login_attempts = 0

show_others.py

from web_users import *

class  Privileges():
    def __init__(self,privileges = ["can add post","can delete post","can ban user"]):
        self.privileges = privileges
    def show_privileges(self):
        print(self.privileges)    

class Admin(uers):
    def __init__(self,first_name, last_name,descireb,number, login_attempts):
        super().__init__(first_name, last_name,descireb,number, login_attempts)
        self. privileges = []
        self.display = Privileges()

main.py
from web_users import *
from web_others import *
z  =  Admin("郑","治","重庆","18105756",0)
z.display.show_privileges()

#9-13 使用 OrderedDict :在练习 6-4 中,你使用了一个标准字典来表示词汇表。请使用 OrderedDict 类来重写这个程序,并确认输出的顺序与你在字典中添加键
#— 值对的顺序一致。
from collections import OrderedDict
p = OrderedDict()
p['int'] = '整型',
p['float'] = "浮点形",
p['double'] = "双浮点",
p['string'] = "字符串",
p['char'] = "单字符",
p['longlong'] = "双长",
p['print()'] = "输出",
p['list'] = "表格",
p['elif'] = "除了 如果",
p['字典'] = "字典就是字典啊",
p['元组'] = "元组就是元组啊"
for v,k in p.items():
    print(v,k)

#9-14 骰子 :模块 random 包含以各种方式生成随机数的函数,其中的 randint() 返回一个位于指定范围内的整数,例如,下面的代码返回一个 1~6 内的整数:
from random import randint
class Die ():
    def __init__(self,sides=6):
        self.sides = sides
    def roll_die(self):
         num = randint(1,self.sides)
         print(num)
p = Die(6)
q = Die(10)
k = Die(20)
for i in range (1,11):
    p.roll_die()
    q.roll_die()
    k.roll_die()

#9-15 Python Module of the Week :要了解 Python 标准库,一个很不错的资源是网站 Python Module of the Week 。请访问 http://pymotw.com/ 并查看其中的目录,在其中找一
#个你感兴趣的模块进行探索,或阅读模块 collections 和 random 的文档。
mark了 下次再看看吧 我先把你刷完

#10-1 Python 学习笔记 :在文本编辑器中新建一个文件,写几句话来总结一下你至此学到的 Python 知识,其中每一行都以 “In Python you can” 打头。将这个文件命名为
#learning_python.txt ,并将其存储到为完成本章练习而编写的程序所在的目录中。编写一个程序,它读取这个文件,并将你所写的内容打印三次:第一次打印时读取整个
#文件;第二次打印时遍历文件对象;第三次打印时将各行存储在一个列表中,再在 with 代码块外打印它们。
file_name = 'learning_python.txt'
file_object= open(file_name,'r', encoding='UTF-8')

content = file_object.read()
print(content)

for line in file_object:
   print(line)

lines = file_object.readlines()
for line in lines:
    print(line.rstrip())

#10-2 C 语言学习笔记 :可使用方法 replace() 将字符串中的特定单词都替换为另一个单词。下面是一个简单的示例,演示了如何将句子中的 'dog' 替换为 'cat'
file_name = 'learning_python.txt'
with open (file_name) as  f:
    content = f.readlines()
for line in content:
    new_line = line.replace('Python','C')
    print(new_line.rstrip())

#10-3 访客 :编写一个程序,提示用户输入其名字;用户作出响应后,将其名字写入到文件 guest.txt 中。
file_name = 'guest.txt'
with open(file_name,'w') as f:
    while 1:
        p = input("输入你的名字")
        if p == 'q':
                break
        else:
            f.write(p)


#10-4 访客名单 :编写一个 while 循环,提示用户输入其名字。用户输入其名字后,在屏幕上打印一句问候语,并将一条访问记录添加到文件 guest_book.txt 中。确保这
#个文件中的每条记录都独占一行。
file_name = 'learning_python.txt'
with open(file_name,'w') as f :
    while 1:
        p = input("输入信息")
        if p == 'q':
            break;
        else:
            f.write(p)
            f.write('\n')

#10-5 关于编程的调查 :编写一个 while 循环,询问用户为何喜欢编程。每当用户输入一个原因后,都将其添加到一个存储所有原因的文件中。
file_name = 'guest.txt'
with open (file_name,'w+') as f:
    while 1:
        p = input("你为什么喜欢编程")
        if p == 'q':
            break
        else:
            f.write(p)

#10-6 加法运算 :提示用户提供数值输入时,常出现的一个问题是,用户提供的是文本而不是数字。在这种情况下,当你尝试将输入转换为整数时,将引
#发 TypeError 异常。编写一个程序,提示用户输入两个数字,再将它们相加并打印结果。在用户输入的任何一个值不是数字时都捕获 TypeError 异常,并打印一
#条友好的错误消息。对你编写的程序进行测试:先输入两个数字,再输入一些文本而不是数字。
def p ():
    try:
        i = int(input())
        j = int(input())
    except ValueError:
        msg = '请输入两个数字'
        print(msg)
    else:
        print(i+j)
p()

#10-7 加法计算器 :将你为完成练习 10-6 而编写的代码放在一个 while 循环中,让用户犯错(输入的是文本而不是数字)后能够继续输入数字。
def p ():
    while 1:
        try:
            i = int(input())
            j = int(input())
        except ValueError:
            msg = '请输入两个数字'
            print(msg)
        else:
            print(i+j)
p()

#10 - 8 猫和狗 :创建两个文件 cats.txt 和 dogs.txt ,在第一个文件中至少存储三只猫的名字,在第二个文件中至少存储三条狗的名字。编写一个程序,尝试读取这些文件,
#并将其内容打印到屏幕上。将这些代码放在一个 try-except 代码块中,以便在文件不存在时捕获 FileNotFound 错误,并打印一条友好的消息。将其中一个文件
#移到另一个地方,并确认 except 代码块中的代码将正确地执行。
file_cats = 'cat.txt'
file_dogs = 'dog.txt'
try:
    with open(file_cats,'r') as object_cats:
        print(object_cats.read())
    with open(file_dogs,'r') as object_dogs:
        print(object_dogs.read())
except FileNotFoundError:
    print("没发现文件")

#10 - 8 猫和狗 :创建两个文件 cats.txt 和 dogs.txt ,在第一个文件中至少存储三只猫的名字,在第二个文件中至少存储三条狗的名字。编写一个程序,尝试读取这些文件,
#并将其内容打印到屏幕上。将这些代码放在一个 try-except 代码块中,以便在文件不存在时捕获 FileNotFound 错误,并打印一条友好的消息。将其中一个文件
#移到另一个地方,并确认 except 代码块中的代码将正确地执行。
file_cats = 'cat.txt'
file_dogs = 'dog.txt'
try:
    with open(file_cats,'r') as object_cats:
        print(object_cats.read())
    with open(file_dogs,'r') as object_dogs:
        print(object_dogs.read())
except FileNotFoundError:
    pass

#10 - 10 常见单词 :访问项目 Gutenberg ( http://gutenberg.org/ ),并找一些你想分析的图书。下载这些作品的文本文件或将浏览器中的原始文本复制到文本文件中。
#你可以使用方法 count() 来确定特定的单词或短语在字符串中出现了多少次。例如,下面的代码计算 'row' 在一个字符串中出现了多少次:
#请注意,通过使用 lower() 将字符串转换为小写,可捕捉要查找的单词出现的所有次数,而不管其大小写格式如何。
#编写一个程序,它读取你在项目 Gutenberg 中获取的文件,并计算单词 'the' 在每个文件中分别出现了多少次。
file_name = 'test_book.txt'
try:
    with open(file_name) as f_obj:
        content = f_obj.read()
        content = content.lower()
except FileNotFoundError:
    print("未发现文件")
else:
    num = content.count('the')
    print(num)

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


file_name = 'numbers.json'
try:
    with open(file_name) as f_obj:
except FileNotFoundError:
    print("没发现文件")
else:
    username = input("输入你的名字")
    json.dump(username,f_obj)
    name = json.load(filename)
    print("“I know your favorite number! It's _____.”",name)

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


file_name='numbers.json'
username = input("输入你喜欢的数字")
try:
    with open(file_name,'w') as f_obj:
        json.dump(username,f_obj)
except FileNotFoundError:
        print("Error")
else:
    with open(file_name) as f_obj:    
        name = json.load(f_obj)
        print("“I know your favorite number! It's _____.”",name)

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


file_name='numbers.json'
try:
    with open(file_name) as f_obj:    
        name = json.load(f_obj)
        print("“I know your favorite number! It's _____.”",name)
        flag = False
except FileNotFoundError:
        print("Error")
else:
    if (flag):
        username = input("输入你喜欢的数字")
        with open(file_name,'w') as f_obj:
            json.dump(username,f_obj)

#10-13 验证用户 :最后一个 remember_me.py
#版本假设用户要么已输入其用户名,要么是首次运行该程序。我们应修改这个程序,以应对这样的情形:当前和最后一次
#运行该程序的用户并非同一个人。
#为此,在 greet_user() 中打印欢迎用户回来的消息前,先询问他用户名是否是对的。如果不对,就调用 get_new_username() 让用户输入正确的用户名。
import json


filename = 'username.json'
def greet_new_name():
        username = input("What is your name? ")
        with open(filename, 'w') as f_obj:
            json.dump(username, f_obj)
        with open(filename,'r') as f_obj:
            username = f_obj.read()
        return(username)

def get_username():
    try:
        with open(filename,'r') as f_obj:
            username = f_obj.read()
    except FileNotFoundError:
        greet_new_name()
    else:
        return(username)

def greet_user():
    name = get_username()
    if name:
        try:
            with open(filename) as f_obj:
                username = json.load(f_obj)
        except FileNotFoundError:
                print("not found!")
        else:
            print("Welcome back, " + username + "!")
    else:
        greet_new_name()
greet_user()

#11-1 城市和国家 :编写一个函数,它接受两个形参:一个城市名和一个国家名。这个函数返回一个格式为 City, Country 的字符串,如
#Santiago, Chile 。将
#这个函数存储在一个名为 city_functions.py 的模块中。
#创建一个名为 test_cities.py 的程序,对刚编写的函数进行测试(别忘了,你需要导入模块 unittest 以及要测试的函数)。编写一个名为 test_city_country() 的
#方法,核实使用类似于 'santiago' 和 'chile' 这样的值来调用前述函数时,得到的字符串是正确的。运行 test_cities.py ,确认测
#试 test_city_country() 通过了。

city_functions.py

def  get_city_country(city,country):
    full_name = city+" "+country
    return full_name.title()


mian.py

import unittest
from city_functions import *

class CityCountryTestCase(unittest.TestCase):
    def test_city_country(self):
        city_country = get_city_country("santiago","chile")
        self.assertEqual(city_country,"Santiago Chile")

unittest.main()

#11-2 人口数量 :修改前面的函数,使其包含第三个必不可少的形参 population ,并返回一个格式为 City, Country -
#population xxx 的字符串,
#如 Santiago, Chile - population 5000000 。运行 test_cities.py ,确认测试 test_city_country() 未通过。
#修改上述函数,将形参 population 设置为可选的。再次运行 test_cities.py ,确认测试 test_city_country() 又通过了。
#再编写一个名为 test_city_country_population() 的测试,核实可以使用类似于 'santiago' 、 'chile' 和 'population=5000000' 这样的值来调用
#这个函数。再次运行 test_cities.py ,确认测试 test_city_country_population() 通过了。

city_functions.py


def  get_city_country(city,country,populution):
    full_name = city+','+country +'-population'+" "+str(populution)
    return full_name.title()


maim.py


import unittest
from city_functions import *

class CityCountryTestCase(unittest.TestCase):
    def test_city_country(self):
        city_country = get_city_country("santiago","chile",5000000)
        self.assertEqual(city_country,"Santiago,Chile-Population 5000000")

    def test_city_country_population(self):
        city_country_country  = get_city_country("santiago","chile",5000000)
        self.assertEqual(city_country_country,"Santiago,Chile-Population 5000000")

unittest.main()

#11 - 3 雇员 :编写一个名为 Employee 的类,其方法 __init__() 接受名、姓和年薪,并将它们都存储在属性中。编写一个名为 give_raise() 的方法,它默认将
#年薪增加 5000 美元,但也能够接受其他的年薪增加量。
#为 Employee 编写一个测试用例,其中包含两个测试方法: test_give_default_raise() 和 test_give_custom_raise() 。使用方法 setUp() ,以免在
#每个测试方法中都创建新的雇员实例。运行这个测试用例,确认两个测试都通过了。
import unittest


#11 - 3 雇员 :编写一个名为 Employee 的类,其方法 __init__() 接受名、姓和年薪,并将它们都存储在属性中。编写一个名为 give_raise() 的方法,它默认将
#年薪增加 5000 美元,但也能够接受其他的年薪增加量。
#为 Employee 编写一个测试用例,其中包含两个测试方法: test_give_default_raise() 和 test_give_custom_raise() 。使用方法 setUp() ,以免在
#每个测试方法中都创建新的雇员实例。运行这个测试用例,确认两个测试都通过了。
import unittest


class Employee():
    def __init__(self,first_name,last_name,annual_pay):
        self.first_name = first_name
        self.last_name = last_name
        self.annual_pay = annual_pay
    def give_raise(self):
        self.annualpay = 5000
        return self.annualpay

class test_EmployeeTestCase(unittest.TestCase) :
    def setUp(self):
        self.Employee = Employee('王','小明',300)
    def test_give_default_raise(self):
        self.assertEqual(self.Employee.annual_pay,300)
    def  test_give_custom_raise(self):
        self.assertEqual(self.Employee.give_raise(),5000)

unittest.main()
posted @   俺叫西西弗斯  阅读(0)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
点击右上角即可分享
微信分享提示