有时候卡住了参考了这个链接:
CSDN:【Python编程: 从入门到实践】习题答案(目录索引)https://blog.csdn.net/qq471011042/article/details/79368237
以及,本书官方的网站,网站附带提供视频资源在B站,还有本书的官方答案在【随书下载】中可以下载
图灵官方:https://www.ituring.com.cn/book/1861 ,十分推荐看官方答案,我是第九章才开始看的,看官方的答案就,写得很标准顺滑总之
再另,我用的是VScode写的
VScode里用python:https://blog.csdn.net/zhangkai950121/article/details/117395333
最后:以下都是边学边码的代码,以一章为单位写的。笔记也在对应的注释里。菜狗本狗,有错误欢迎指正
每一章的习题代码和一些注释笔记
chap3 列表简介
#3-1 存一些名字,命名为names。依次访问该列表中的每个元素,从而将每个姓名都打印出来
names=['mango','banana','raisins']
print(names)
#3-2 为每人打印一条消息。每条消息都包含相同的问候语,但抬头为相应朋友的姓名
for name in names:
print(name.title()+',would you like to eat some food')
print('=========================================')
##知识点
#删除,包括del、pop()、remove()
#插入,包括insert,append
#3-4 创建列表,邀请至少三个人共进晚餐
invitation=['AAA','BBB','CCC']
for name in invitation:
print(name+',we want to invite you to dinner')
#3-5 3-4基础上有个人来不了,print显示;另邀请一个替换,并打印信息
print('AAA can not be present')
del invitation[0]
invitation.insert(2,'DDD')
for name in invitation:
print(name+',we want to invite you to dinner' )
#3-6 3-5基础上,print找到更大餐桌,insert一位到开头,一位中间,append一位末尾,打印
print('we have a larger table')
invitation.insert(0,'111')
invitation.insert(2,'222')
invitation.append('333')
for name in invitation:
print(name+',we want to invite you to dinner' )
#3-7 缩减名单,pop()删除直至两人且删一个发一个消息,剩下两人打印消息,最后del删除,名单空
print(invitation)
print('sorrry,the table won\'t arrive on time')
i=len(invitation)
print(i)
while i>2:
last_name=invitation.pop(i-1)
print(last_name+',sorry,you are out')
i=i-1
for name in invitation:
print(name+',you are lucky')
del invitation[1]
del invitation[0]
print(invitation)
print('======================================')
##知识点:
#sort()永久性按字母排列,reverse=True反向排列,reverse()永久性反向,sorted()临时排列
#len()列表长度
#3-8 五个地名,原始顺序打印、sorted()、sort()、reverse()排列打印
travel=['EEE','AAA','RRR','NNN','PPP']
sorted_list=sorted(travel)
print(sorted_list)
print(travel)
#travel.sort(reverse=True)
travel.sort()
print(travel)
travel.reverse()
print(travel)
chap4 操作列表
##chap4 操作列表
#####知识点:for循环、缩进
#4-1 三个吃的,for循环打印吃的名字、打印名字和一句话、单独打印一句话,简单不做
#4-2 三个动物,打印名字,打印句子,单独打印一句话
animals=['corgi','goldfish','cat']
print(animals)
for animal in animals:
print('A '+animal+' would make a great pet')
print('Any of these anmials would make a great pet')
print('==============================================')
#####知识点:数值列表
#range(a,b)生产a到b-1的数字,list(range())生产列表,range(a,b,c)c为间隔数字
# **表示乘方运算 min\max\sum
#列表解析 squares=[value**2 for value in range(1,11)] 即综合为简短代码
#4-3 for循环打印1-20
for number in range(1,21):
print(number,end='、') #end='、 ' 表示将结果打印为一行且以、间隔
#4-4 列表包含1-1000000,for打印
#for number in range(1,1000001):
#print(number,end=' ') #ctrl+c可结束计算
#4-5 计算1-一百万总和,以及最大和最小值
millions=list(range(1,1000001))
print('\n') #这里是因为前面1-20设置、间隔,故在20后不会换行,所以自己加一个
print(+max(millions))
print(min(millions))
print(sum(millions))
#4-6 range()创建1-20的奇数,for打印
odd_number=range(1,21,2)
for odd in odd_number:
print(odd,end=' ')
#4-7 列表包含3-30中被3整除的数字,for打印
print('\n')
three_division=range(3,31,3)
for three in three_division:
print(three,end=' ')
#4-8 2**3表示2的立方,列表1-10的立方并用for循环打印
cubic=[value**3 for value in range(1,11)] #立方解析,输出为列表
print('\n')
print(cubic)
for value in range(1,11):
value=value**3
print(value,end=' ')
#####知识点:切片索引
#[a:b]从a开始,索引到b [:b]从头开始,检索b [a:]从a开始检索到最后 [-3:]从最后第三个开始
#[:]可用以复制列表,得俩列表,a_list=b_list则是直接将a关联到b,两个实际为同一列表
#4-10 任选前面的程序,切片打印前三、中间三和后三个元素
print('\n')
print('the frist three items in the list are: ')
print(cubic[0:3])
print('Three items from the middle of the list are: ')
print(cubic[4:7])
print('The last three items in the list are: ')
print(cubic[-3:])
#4-11 创建一个副本,即复制一个列表,分别在两个列表中新增一个元素,for循环打印
new_cubic=cubic[:]
new_cubic.append('000')
cubic.append('999')
print('My favorite numbers are: ')
for number in cubic:
print(number,end=' ')
print('\n')
print('my friend\'d favorite number is: ')
for number in new_cubic:
print(number,end=' ')
#####知识点:元组
#元组tuple(a,b)即有a和b两元素,不能直接用tuple[0]=c来修改元素,可以重新赋值
#4-13 五个吃的存元组,for打印,修改一个,重新赋值两种吃的,for打印
restaurant=('banana','grabe','peach','apple','noodle')
for food in restaurant:
print(food,end=' ')
#restaurant[0]='ahh' #报错用的
lst=list(restaurant)
lst[0]='rice'
lst[3]='tomato'
restaurant=tuple(lst)
print('\n new meau are: ')
print(restaurant,end=' ')
#####知识点:代码格式
#改进提案(Python Enhancement Proposal,PEP
#https://peps.python.org/pep-0008/,PEP规则,就是代码规范
#修改固定80字符IDLE不可,pycharm可以,vscode也可以
chap5 if语句
######chap5 if语句
#==================================
#####知识点:条件测试
#每条if语句的核心都是一个值为True或False的表达式,这种表达式被称为条件测试
#相等运算符==,检查时可用lower()规避大小写冲突,不等运算符!=,
#关键词and和or,关键词in和not in检查包含与否,
#布尔表达式,返回结果True和False
#===========================================
#5-1 自己搞10个条件测试,结果True和flase对半开
alphabet=['aa','bb','cc']
test='aa'
if test == alphabet[0]:
print(test)
if test!=alphabet[1]:
print(test)
print(test==alphabet[0]) #print在这里直接返回布尔判断true和false
print(alphabet[0]=='aa'and alphabet[1]!='bb')
print(test in alphabet)
print('cc' not in alphabet)
print('aa' in test or 'bb' in test)
#5-2 条件测试:字符串相等于否、lower()测试、数字等不等大小于等、and和or、特定值测试
uppercase_letter='AA';
print(uppercase_letter.lower()==test)
print('数字测试')
print(25>30)
print(2<3)
print(2>=2)
print(2<=1)
#===知识点:if-elif-else,elif只在if未通过测试时运行,三选一;
#===else可以省略有时候,只存在if-elif,检测必要条件成立否,可设置多个elif,多选一
#===独立测试,就只要多个if,逐个判断
#==============================================
#5-3 创建外星人变量,if检测颜色是否为绿色,是打印,
alien_color=['green','yellow','red']
if 'green' in alien_color:
print('you receives 5 points')
#5-4 if-else,绿色获5积分,不是获10积分,
if 'green' in alien_color:
print('you receives 5 points')
else:
print('you receives 10 points')
#5-5 if-elif-else
if 'green' in alien_color:
print('you receives 5 points')
elif 'yellow' in alien_color:
print('you receives 10 points')
else:
print('you receives 10 points')
#5-6 age,if-elif-else
age_test=20
if age_test<2:
print('he is a baby')
elif age_test<4:
print('he is learning to walk')
elif age_test<13:
print('he is a child')
elif age_test<20:
print('he is a teenager')
elif age_test<60:
print('he is an adult')
else:
print('he is an older')
#===知识点:检查空元素或不存在的元素
#5-8 5个用户名列表,含admin,打印问候语,admin区别打印
uesr_administrator=['aa','bb','admin','cc','dd']
if uesr_administrator:
for user in uesr_administrator:
if user =='admin':
print('Hello '+user+', would you like to see a status report?')
else:
print('Hello '+user+', thank you for logging in again')
else: #5-9 添加if语句检查用户列表是否为空
print('We need to find some users!')
#5-10 两个分别5人的新旧用户名列表,遍历新的,如果已存在,打印消息,不区分大小写
current_users=['aa','bb','cc','dd','ee']
new_users=['AA','ss','ww','dd','oo']
for user in new_users:
if user.lower() in current_users:
print('the user name '+user+' already exists')
else:
print('you can use this user name: '+user)
#5-11 存数字1-9,遍历并打印每个数字的序数,if-elif-else
numbers=list(range(1,6))
for number in numbers:
if number == 1:
print('1st')
elif number == 2:
print('2nd')
elif number == 3:
print('3rd')
elif number == 4:
print('4th')
elif number == 5:
print('5th')
chap6 字典
#====================================
#####chap6 字典
#====================================
#===知识点:键-值对,即为字典,如 Mr.Li={'age':2,'gender':'male}
#访问字典:Mr.Li['age'];添加键-对:Mr.Li['address']='China';空字典:A={};
#修改值:Mr.Li['address']='UK';删除键-值:del;
#=============================================
#6-1 字典存储人信息
new_friend={
'frist name':'Hua',
'last_name':'Li',
'age':20,
'city':'Beijing'
}
#6-2 字典存储5个人喜欢的数字
favorite_number={
'Li':1,
'Huang':2,
'Qin':3,
'Zhu':4,
'Hu':5
}
#6-3 5个编程词汇及含义,打印
programming_vocabulary={
'and':'连接',
'list':'列表',
'range':'生成范围内数字',
'if':'条件判断',
'in':'包含'
}
for key,value in programming_vocabulary.items(): #方法item()
print(key+' : '+value+'\n') #6-4 前面的词汇表,print循环遍历输出
#===知识点:方法key(),value();排序sorted();
# 剔除重复项,集合set(programming_vocabulary.value()),即去除value里的重复项
#=====================================================
#6-4 再添加5个python术语
programming_vocabulary['or']='或'
print(programming_vocabulary)
#6-5 创建河流字典,三条大河和流经地,循环打印每条河流;分别循环打印河流和国家
river_country={
'the yellow river':'Qinghai', #这里是列表和字典的嵌套
'the Yangtze river':'Jiangsu',
'nile':'egypt'
}
print('=====6-5=====')
for k,v in river_country.items():
print('The '+k+'runs through '+v)
for river in river_country.keys():
print(river)
for country in river_country.values():
print(country)
#6-6 字典,名单,遍历名单
print('=====6-6=====')
favorite_languages = {
'amada':'C',
'jacky':'java',
'frank':'c++',
'polly':'php',
'maily':'.net'
}
investigator_lists=['amada','aa','jacky','bb']
for investigator in investigator_lists:
if investigator in favorite_languages.keys():
print(investigator+',thanks')
else:
print('Dear '+investigator+',sincerely invite you to participate in the survey')
#===知识点:嵌套:字典和列表的包含关系,或者字典和字典
#=================================================
#6-7 6-1基础上再加两个表示人的字典,都存在people列表中,遍历打印每个人信息
print('=====6-7=====')
friend_1st={
'frist name':'Hua',
'last_name':'Li',
'age':20,
'city':'Beijing'
}
friend_2nd={
'frist name':'Fei',
'last_name':'Zhang',
'age':18,
'city':'Chengdu'
}
friend_3rd={
'frist name':'Bei',
'last_name':'Liu',
'age':25,
'city':'Guangzhou'
}
people=[friend_1st,friend_2nd,friend_3rd]
for name in people:
print(name)
#6-8 同6-7,主语换成了宠物而已
#6-9 字典嵌套列表,favorite_places的字典,人作为键,三个喜欢地方为值,遍历打印
print("=====6-9=====")
favorite_places={
'Lihua':['Guangzhou','Roman','UK'],
'Xiaoming':['Suzhou','Xinjiang','Italy'],
'Zhangsan':['Xizang','Finland','Norway']
}
for name,places in favorite_places.items():
print(name.title()+"'s favorite places are: ")
for place in places:
print("\t"+place.title())
#6-10 改编6-2,同6-9类似
print("=====6-10=====")
favorite_number={
'Li':[1,2,3],
'Huang':[2,3],
'Qin':[3,4],
'Zhu':[4,5],
'Hu':[5,6]
}
for name,numbers in favorite_number.items():
print("\n"+name.title()+"'s favorite numbers are: ")
for number in numbers:
print("\t"+str(number),end=' ')
#6-11 字典嵌套字典,几个城市,城市包含国家、人口数和城市事实,遍历打印
print("\n=====6-11=====")
cities={
'Beijing':{
'country':'China',
'population':'1.4 billion',
'fact':'beauty'
},
'New York':{
'country':'The United States',
'population':'0.33 billion',
'fact':'Well'
}
}
for city,information in cities.items():
print("The information about "+city+" is as follow: ")
for k,v in information.items():
print("\t"+k.title()+" : "+v.title())
chap7 用户输入和while循环
#=============================================
#=====chap7 用户输入和while循环
#=============================================
#===知识点:input()输入,将结果视为字符串;int()输入,结果视为数值;求余数运算符【%】
#==============================================
#7-1 input输入:编写程序模拟租车
print("=====7-1=====")
car_rental=input("What kind of car would you like to rent ")
print("Let me see if I can find you a "+car_rental)
#7-2 int数字转换:模拟订餐,超过8人打印没有空桌
print("=====7-2=====")
restaurant_reservation=input("How many people are there for dinner ")
restaurant_reservation=int(restaurant_reservation)
if restaurant_reservation>=8:
print("sorry,we have no vacant table")
else:
print("welcome")
#7-3 输入数字判断是否是10的整数倍
print("=====7-3=====")
number_aliquot=input("show me a number ")
number_aliquot=int(number_aliquot)
if number_aliquot % 10 == 0:
print("this number can be divisible by 10 ")
else:
print("Bye")
#===知识点:while循环
#===结束循环:设置标志,如a=true;while a:或者用break直接结束;continue回到循环开头
#===crtl+C,关闭运行的程序
#===========================================
#7-4 输入披萨配料,并提示quit结束
print("=====7-4=====")
pizza_toppings="enter the topping you want to add: "
pizza_toppings+="\nenter 'quit' when you are finished: "
while True:
topping=input(pizza_toppings)
if topping=='quit':
break
else:
print(topping+" has been added to pizza")
#7-5 循环/input/int/break:询问用户年龄,输出对应票价
print("=====7-5=====")
ticket="tell me how old you are: "
while True:
age=input(ticket)
age=int(age)
if age<3:
print("free")
break
elif age<12:
print("$10")
break
else:
print('$15')
break
#7-6 while中用条件测试结束循环、active作为标志、break在quit时
print("=====7-6=====")
pizza_toppings="enter the topping you want to add: "
pizza_toppings+="\nenter 'quit' when you are finished: "
active=True
while active:
topping=input(pizza_toppings)
if topping=='quit':
break #active=Flase也可行
else:
print(topping+" has been added to pizza")
#===知识点:for循环不建议修改列表,但while循环可以
#===可移动元素;可删除列表里所有特定元素remove();
#===============================================
#一个没搞明白的示例
print("=====没搞明白的示例=====")
responses={}
polling_active=True
while polling_active:
#输入被调查者的名字和回答
name=input("\nwhat is your name? ")
response=input("which mountain would you like to climb someday?")
#存储回答到字典中 ???????????就是这里没看懂
responses[name]=response
#其他接受调查的人
repeat=input("巴拉巴拉(yes/no)")
if repeat=='no':
polling_active=False
#调查结果输出
print("------Poll Results-------")
for name,response in responses.items():
print(name+" would like to climb "+response)
#7-8 三明治菜单和制作完成两个列表,依次从菜单栏移动到完成列表,并输出完成提示
print("=====7-8 & 7-9=====")
sandwich_orders=['aa','bb','cc','aa','aa']
finished_snadwiches=[]
while sandwich_orders: #7-9 某物出现三次以上,while循环删掉
while 'aa' in sandwich_orders:
sandwich_orders.remove('aa')
if 'aa' not in sandwich_orders:
finish=sandwich_orders.pop()
print("I made your "+finish+" sandwich")
finished_snadwiches.append(finish) #前面只是弹出来了,但并没有添加到完成列表里
print(sorted(finished_snadwiches))
#7-10 调查度假圣地
print("=====7-10=====")
vocation_places={}
survey=True
while survey:
name=input("what's your name? ")
place=input("If you could visit one place in the world, where would you go?")
vocation_places[name]=survey
over=input("thanks for your reply.Have a drink(yes/no)")
if over == 'no':
survey=False
print(vocation_places)
chap8 函数
#==========================================
#===chap8 函数
#==========================================
#===知识点:def()定义函数,文档字符串""" """三引号做注释;实参和形参
#=======================================================
#8.1 编辑函数指出本章所学内容
print("=====8.1=====")
def display_message():
print("what i learned is function ")
display_message();
#8.2 code a function to tell us your favorite book
print("=====8.2=====")
def favorite_book(title):
print("One of my favorite books is "+title)
favorite_book("Alice in Wonderland")
#===知识点:位置实参,就是多个参数传递给函数,注意参数对应的位置
#==========关键字实参,将函数中的形参在实参中写一下,如def pet(type,age),最后pet(type='a',age='12')
#==========默认值:即给形参指定值。def pet(age,type='dog'),注意默认值在后面.函数只需提供另一个,即pet('12')
# 8.3 编写T恤函数。接受尺码和字样。位置实参和关键字实参
print("=====8.3=====")
def make_shirt(size,word):
"""位置和关键字实参"""
print("The T-shirt's "+size+" is "+word)
make_shirt("16","'i wanna sleep'")
make_shirt(size='16',word="'no, you don't'")
#8.4 修改8.3,大中小号T恤,默认值
print("=====8.4=====")
def make_shirts(size,word):
print("The T-shirt's "+size+" is "+word)
sizes=('large','medium','small')
for size in sizes:
make_shirt(size,word='i love python')
#8.5 城市+所属国默认值
print("=====8.5=====")
def describe_city(city,country='China'):
print(city.title()+" is in "+country.title())
cities=('Chengdu','Chongqing','Guizhou')
for city in cities:
describe_city(city)
#===知识点:函数中添加返回值return();设置形参可接受空值,用if-else的布尔值判断
#==========返回字典。while循环
# 8.6 城市和国家,返回固定格式
print("=====8.6=====")
def city_country(city,country):
full_string='"'+city+', '+country+'"'
return full_string
a=city_country('aa','bb')
print(a)
'''下面的方法不成功,反应不出来
city_country={'Chengdu':'China',
'New York':'America',
'London':'UK'}
for k,v in city_country.items():
city_country(k,v)
print(city_country)'''
#8.7 & 8.8 ①music album;②add an optional parameter;③use dict
print("=====8.7=====")
def make_album(singer_name,album_name,number_songs=''): #这两个''挺重要
album={}
if number_songs:
album['Singer name: ']=singer_name
album['Album name: ']=album_name
album['Total number of songs: ']=number_songs
#the next code can run directly after deleting three lines before
#album=singer_name+':'+album_name+"the total number of songs:"+number_songs
return album
else:
album['Singer name: ']=singer_name
album['Album name: ']=album_name
#the next code is similar to the above
#album=singer_name+' : '+album_name
return album
while True:
print('type your favorite singer and his/her album name')
print("enter 'q' to quit this program or nothing to continue")
s_name=input('singer_name: ')
if s_name=='q':
break
a_name=input('album_name: ')
if a_name=='q':
break
num_songs=input("total number of songs :")
get_album=make_album(s_name,a_name,num_songs)
print(get_album)
#知识点:①用列表存储信息,调用函数;②副本传递[:]
#==========================================================================
#8.9 函数调用列表
print('=====8.9=====')
def show_magicians(names):
for name in names:
print('hallo, '+name)
magicians=['aa','bb','cc']
#show_magicians(magicians) #to avoid duplicating with function behind
#8.10 8.9基础上,增加一个函数
def make_great(name_list,change_names): #change_name是关键,不然不好获得返回值
while name_list:
name=name_list.pop()
name="The Great "+name
change_names.append(name)
change_names=[]
#make_great(magicians,change_names) #similarly to the 8.9 note
#show_magicians(change_names)
#8.11 8.10基础上,传递副本,返回值另存列表,共俩,改名前和后
make_great(magicians[:],change_names)
show_magicians(magicians)
show_magicians(change_names)
#知识点:①【*】符号可以接受多次实参,带*参数放后面;②【**】创建字典
#====================================================================
#8.12 三明治函数,
print('=====8.12=====')
def make_sandwich(*toppings):
print("Making a sandwich with the following toppings:")
for topping in toppings:
print("- "+topping)
make_sandwich('aa')
make_sandwich('fadsfd')
#8.13 改程序,指名道姓,和三对描述性键值对
print('=====8.13=====')
def build_profile(frist,last,**user_info):
profiles={}
profiles['frist_name:']=frist
profiles['last_name:']=last
for k,v in user_info.items():
profiles[k]=v #这里蛮神奇的
return profiles
user_profiles=build_profile('aa','bb',
food='sandwich',drink='water',bed='sleep')
print(user_profiles)
#8.14 汽车字典存储数据
print('=====8.14=====')
def make_car(automaker,modal,**car_info):
profiles={}
profiles['Automaker:']=automaker
profiles['Car_Modal:']=modal
for k,v in profiles.items():
profiles[k]=v
return profiles
car=make_car('subaru','outback',color='blue',tow_package=True)
print(car)
#知识点:导入函数
#①import XXXXX; ②from XXX import XXXX;
#③from XX import xxx as bb ④import xxx as xxx
#导入模块所有函数:【from xxx import *】,*即代表所有。不推荐一般,万一和已有函数重了
#==============================================================================
chap9 类
#===============================================================
#====chap9 类
#===============================================================
#知识点:①创建和使用类:class XXX().XXX首字母大写
# ②类中的函数称为方法。如def _init_(self,name,age):首位下划线避免方法和python自带方法冲突
# ③self是必须的,类似定义了后两个东西的主体是谁,用到时也好调用
# ④可通过实例访问的变量即属性,self.name=name,
#==========================================================================
#9.1 创建餐馆类,三个方法,两个属性
print('=====9.1=====')
class Restaurant():
def __init__(self,restaurant_name,cuisine_type): #注意,是前后两根下划线!!
self.name=restaurant_name
self.type=cuisine_type
def describe_restaurant(self):
print("the name of restaurant is: "+self.name.title())
print("the cuisine are: "+self.type.title())
def open_restaurant(self):
print("welcome")
have_meal=Restaurant('aa','bb')
print(have_meal.name.title()) #查看属性
print(have_meal.type)
have_meal.describe_restaurant() #调用方法
have_meal.open_restaurant()
#9.2 9.1创建三个实例.都是重复的就只写一个
print('=====9.2=====')
have_breakfast=Restaurant('bb','vv')
print(have_breakfast.name+','+have_breakfast.type)
#9.3 创建user类,两个属性,两个方法
print('=====9.3=====')
class User():
def __init__(self,frist_name,last_name):
self.frist_name=frist_name
self.last_name=last_name
def describe_user(self):
print("Frist name: "+self.frist_name)
print("Last name: "+self.last_name)
def greet_uesr(self):
print("hallo,"+self.frist_name+self.last_name)
people_one=User('aaa','bbb') #这就是一个实例
people_one.describe_user()
people_one.greet_uesr()
#知识点:修改属性的值:①直接修改属性。②方法中增加一个属性修改。③增加一个方法修改
#=========================================================================
#9.4 9.1程序,新增默认值为0的参数;新增方法可设置就餐人数;递增方法
print('=====9.4=====')
class cafe():
def __init__(self,restaurant_name,cuisine_type): #注意,是前后两根下划线!!
self.name=restaurant_name
self.type=cuisine_type
def describe_restaurant(self,number_served): #方法中增加一个属性
self.number_served=number_served
print("the name of restaurant is: "+self.name.title())
print("the cuisine are: "+self.type.title())
print("Number served: "+str(self.number_served))
def set_number_served(self,set_number_served): #增加一个方法
self.set_number_served=set_number_served
def increment_number_served(self,increment_number): #③增加一个方法
self.set_number_served+=increment_number
def read_restaurant(self):
print("now the number of served is "+str(self.set_number_served))
restaurant=cafe('zzz','ddd')
restaurant.describe_restaurant(0)
restaurant.set_number_served(13)
restaurant.read_restaurant()
restaurant.increment_number_served(2)
restaurant.read_restaurant()
#9.5 9.3基础上,增加属性,方法将属性值加1,又一方法将属性值减1
print("=====9.5=====")
class User2():
def __init__(self,frist_name,last_name):
self.frist_name=frist_name
self.last_name=last_name
self.login_attempts=0
#下一行不能用,用了self.login_attempt变成字符串,在方法increcet中报错
#self.login_attempts=login_attempts
def describe_user(self):
print("Frist name: "+self.frist_name)
print("Last name: "+self.last_name)
def increcent_login_attempts(self,login_attempts):
self.login_attempts+=login_attempts
def reset_login_attempts(self):
self.login_attempts=0
def print_uesr(self):
print("now the number of users are "+str(self.login_attempts))
uuu=User2('aa','bb')
i=10
while i>5:
uuu.increcent_login_attempts(1)
uuu.print_uesr()
i=i-1
while i>0:
uuu.reset_login_attempts()
uuu.print_uesr()
i=i-1
#知识点:超类superclass,实际就是继承另一个类的方法
#=======================================================================
#9.6 冰淇淋类,继承9.4的餐馆类,添加一个口味属性
print("=====9.6=====")
class IceCreamStand(cafe): #包含父类名很重要
def __init__(self,restaurant_name,cuisine_type):
"""initialize the properties"""
super().__init__(restaurant_name,cuisine_type) #继承父类
def cream_flavors(self,*flavors):
for flavor in flavors:
print("the flavor of ice cream has "+str(flavor)) #这里不加str会报错
flavors=['aa','bb','vc']
ice_cream=IceCreamStand('DairyQueen','iiii')
ice_cream.cream_flavors(flavors)
#another way
class IceCreamStand2(cafe): #包含父类名很重要
def __init__(self,restaurant_name,cuisine_type):
"""initialize the properties"""
super().__init__(restaurant_name,cuisine_type) #继承父类
def cream_flavors(self): #这里打印出来就是字符串,而不是上一个里面的列表
flavors=['aa','bb','vc']
for flavor in flavors:
print("the flavor of ice cream has "+(flavor))
ice_cream2=IceCreamStand2("DairyQueen",'aaaa')
ice_cream2.cream_flavors()
#9.7 管理员,继承9.5的user类
print("=====9.7=====")
class Admin(User):
def __init__(self, frist_name, last_name):
super().__init__(frist_name, last_name)
self.privileges=["can add post","can delete post","can ban user"]
def show_privileges(self):
print("the administration of this computer is "+self.frist_name+self.last_name)
for privilege in self.privileges:
print("the admin have:"+privilege)
PC_admin=Admin('zhang','san')
PC_admin.show_privileges()
#9.8 一个类调用另一个类,
print("=====9.8=====")
class Admin2(User):
def __init__(self, frist_name, last_name):
super().__init__(frist_name, last_name)
self.privileges=["can add post","can delete post","can ban user"]
self.privilege=Privileges() #调用另一个类
class Privileges():
privileges=["can add post","can delete post","can ban user"]
def show_privileges(self):
for privilege in self.privileges:
print("the admin have:"+privilege)
pc_admin=Admin2("zhao",'si')
pc_admin.privilege.show_privileges() #两个类见的调用
#9.9 书上例子增加。多个类继承和调用。
print("=====9.9=====")
class Car():
def __init__(self,make,modal,year):
self.make=make
self.model=modal
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 updata_odometer(self,mileage):
if mileage>=self.odometer_reading:
self.odometer_reading=mileage
else:
print("you can not roll back an odometer")
def increment_odometer(self,miles):
self.odometer_reading+=miles
class ElectricCar(Car):
def __init__(self, make, modal, year):
super().__init__(make, modal, year)
self.battery_size=Battery() #调用另一个类
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 appeoximately "+str(range)
message+=" miles on full charge"
print(message)
def upgrade_battery(self):
if self.battery_size!=85:
self.battery_size=85
my_car=ElectricCar('tesla','model','2020')
my_car.updata_odometer(100)
my_car.read_odometer()
my_car.battery_size.get_range()
my_car.battery_size.upgrade_battery()
my_car.battery_size.get_range()
#知识点:可以将函数和类,另存为一个模块,如car.py,
# 这样就可:from car import Car\from car import ElectricCar\from car import Car,ElectricCar
#导入整个模块,import car
#导入模块中所有类,from xxx import * [不推荐]
#==========================================================================
#9.10-9.13d导入模块都没有做
#9.14 rangom函数
print("=====9.14=====")
from random import randint
class Die():
def __init__(self):
self.sides=6
def roll_die6(self):
print(randint(1,6),end=' ')
def roll_die10(self):
print(randint(1,10),end=' ')
def roll_die20(self):
print(randint(1,20),end=' ')
roll_dice=Die()
for i in range(10):
roll_dice.roll_die6()
chap10 文件和异常
#10.1 编程程序读取自己存储的文本文件
print("=====10.1=====")
filename=r"E:\AHHHH\笔记本\Python\learn_python\learn_python_chap10.txt"
with open(filename) as f: #整个文件打印
lines=f.read()
for i in range(3):
print(lines)
with open(filename) as f:
for line in f: #遍历打印,print在每行自带一个换行符,每行末尾也有一个,故消去一个
print(line.rstrip())
with open(filename) as f: #在with结构外打印,
lines=f.readlines() #读取存为列表
for line in lines:
print(line.strip())
#10.2 替换python为java
print("=====10.2=====")
for line2 in lines:
line2=line2.replace('python','Java')
print(line2.strip())
#知识点:【'w'写入模式,'r'读取,'a'添加模式,'r+'读加其他模式】。在open(filename,'x')用
# 默认以只读方法打开文件。且,只能写入【字符串】。'a'只会在末尾增加内容
# filename.write()就可以写东西了,默认没有【换行符】
#============================================================================
#10.3 写访客
print("=====10.3======")
filename=r'E:\AHHHH\笔记本\Python\learn_python\guest.txt'
#with open(filename,'r') as f:
# name=input("tpye your user name: ")
# f.write(name) #存储的需要是字符串,把上一句input放这里name处,不成立
#10.4 访客名单加while循环
print("=====10.4=====")
contents=("Please input your name \n")
contents+=("enter 'q' to close this programe: ")
while True:
name=input(contents)
if name=='q':
break
else:
with open(filename,'a') as file: #循环多次写入,用【a】
file.write(name+'\n')
#10.5 编程调查
print("=====10.5======")
filename=r'E:\AHHHH\笔记本\Python\learn_python\survey.txt'
print("tpye 'q' to end this program")
while True:
reason=input("write your reason about why you choose to code: ")
if reason=='q':
break
else:
with open(filename,'a') as f:
f.write(reason+'\n')
#知识点:处理异常,try-except板块,try-except-else
# 程序发生异常时不做任何表示,则可以用加上pass语句在try-except里
# split(),将字符串划定为多个单词。
#===================================================================
#10.6 加法运算.当输入的不是数字时,报错
print("=====10.6=====")
def caculate():
try:
print("please type two number for caculate")
frist_num=input("frist_number: ") #input输入的是字符串,需转换
frist_num=int(frist_num)
second_num=input("second_number: ")
second_num=int(second_num)
except ValueError:
print("Your input is not in number format, please check again")
else:
add_num=frist_num+second_num
print("the sum is: "+str(add_num)) #计算完后,add_num是int形式,要转为str
caculate()
#10.7 加法计算器。改编10.6,
print("=====10.7=====")
def caculate2():
print("enter 'q' to end this program")
while True:
try:
print("please type two number for caculate")
frist_num=input("frist_number: ")
if frist_num=='q':
break
else:
frist_num=int(frist_num)
second_num=input("second_number: ")
if second_num=='q':
break
else:
second_num=int(second_num)
except ValueError:
print("Your input is not in number format, please try again")
else:
add_num=frist_num+second_num
print("the sum is: "+str(add_num))
caculate2()
#10.8 创建猫和狗txt,读取文件并打印,文件不存在时返回错误
print("=====10.8=====")
import os
def read_cat_dog():
#下面是借鉴的这个链接代码:https://blog.csdn.net/ayouleyang/article/details/102746267
#主要是打开指定路径下多个文件。官方描述在这里:https://pymotw.com/3/os/index.html
path="E:\AHHHH\笔记本\Python\learn_python"
files=os.listdir(path)
for file in files:
try:
if file=='cats.txt'or file =='dogs.txt':
position=path+'\\'+file
print(position)
with open(position) as f:
contents=f.readlines()
print(contents," ")
except FileNotFoundError:
print("can not find your file")
read_cat_dog()
#10.9 修改10.8代码,用except-pass传递
print("=====10.9=====")
import os
def read_cat_dog2():
#下面是借鉴的这个链接代码:https://blog.csdn.net/ayouleyang/article/details/102746267
#主要是打开指定路径下多个文件。官方描述在这里:https://pymotw.com/3/os/index.html
path="E:\AHHHH\笔记本\Python\learn_python"
files=os.listdir(path)
for file in files:
try:
if file=='cats.txt'or file =='dogs.txt':
position=path+'\\'+file
print(position)
with open(position) as f:
contents=f.readlines()
print(contents," ")
except FileNotFoundError:
pass
read_cat_dog2()
#知识点:存储数据,模块JSON(JSON(JavaScript Object Notation)
# json.dump,存储文件,json.load,读取文件
# 重构,将代码改进,比如改为几个有关系的函数
#========================================================================
#10.11 喜欢的数字
print("=====10.11=====")
import json
favorite_num=input("\nwhat is your favorite number: ")
filename=r'E:\AHHHH\笔记本\Python\learn_python\\10.11favorite_number.json' #后缀json
with open(filename,'w') as f:
json.dump(favorite_num,f)
print("Done")
with open(filename) as f:
favorite_number=json.load(f)
print("your number is: "+favorite_number)
#10.12 合并10.11的程序.数字存在就输出,不然就输入
print("=====10.12=====")
import json
def favorite_number():
filename=r'E:\AHHHH\笔记本\Python\learn_python\\10.12favorite_number.json' #后缀json
try:
with open(filename) as f:
favorite_num=json.load(f)
print("your number is "+favorite_num)
except:
favorite_num=input("\nwhat is your favorite number: ")
with open(filename,'w') as f:
json.dump(favorite_num,f)
print("the input number is "+favorite_num)
favorite_number()
#10.13 修改例子程序
#这个程序有个问题是对于已存在用户名,只限于一个名字,两个报错。没有做进一步修改
print("=====10.13======")
import json
def get_stored_username():
filename=r'E:\AHHHH\笔记本\Python\learn_python\\10.13username.json'
try:
with open(filename) as f:
username=json.load(f)
except FileNotFoundError:
return None
else:
return username
def get_new_username():
username=input("what is your name ")
filename=r'E:\AHHHH\笔记本\Python\learn_python\\10.13username.json'
with open(filename,'a') as f:
json.dump(username,f)
return username
def greet_user():
username=get_stored_username()
if username:
print("your username is: "+username)
"""验证用户名正确性"""
make_sure=input("type y/n to make sure your username is right: ")
if make_sure=='y':
print("welcome back! "+username)
else:
print("sorry, you need to input a right username")
username=get_new_username()
print('welcome! '+username)
else:
username=get_new_username()
print("hallo! "+username)
greet_user()
chap11 测试代码
每一小题的测试建议把上一题注释掉再运行
#==========================================================================
#chap11 测试代码
#===========================================================================
#知识点:单元测试:检查函数某方面有无问题;测试用例:一组单元测试;
# 全覆盖式测试用例:一整套单元测试
# 模块unittest,unittest.TestCase类,方法assertEqual:两字符串是否一致
#=========================================================================
#11.1 接受国家和城市的函数
print("=====11.1=====")
def country_city(country,city):
combine_string=country+", "+city
return combine_string
import unittest
class TestCityCountry(unittest.TestCase): #除了具体函数,其他都是,规定写法
def test_city_country(self):
combine=country_city('santiago','chile')
self.assertEqual(combine,'santiago, chile')
unittest.main()
#11.2 在11.1基础上加一个人口形参,修改代码
print("=====11.2=====")
import unittest
def country_city_population(country,city,population=0): #就直接写在这里不另存文件调用了
if population:
combine_string=country+", "+city+"-population="+str(population)
else:
combine_string=country+", "+city
return combine_string
class TestCityCountry2(unittest.TestCase): #除了具体函数,其他都是,规定写法
def test_city_country(self):
combine=country_city_population('santiago','chile')
self.assertEqual(combine,'santiago, chile')
def test_city_country_poputlation(self):
combine=country_city_population('santiago','chile',population=5000000)
self.assertEqual(combine,'santiago, chile-population=5000000')
unittest.main()
#知识点:各种断言方法
# self.assertEqual(a,b)
# self.assertNotEqual(a,b)
# self.assertTrue(x)
# self.assertFalse(x)
# self.assertIn(item,list)
# self.assertNotIn(item,list)
#知识点:setUP()方法,创建一系列实例并设置属性。相比于每个方法中都创建实例和属性要简便
#===================================================================
#11.3 雇员
print("=====11.3=====")
class Employee():
def __init__(self,frist_name,Last_name,annual_salary):
self.frist_name=frist_name
self.last_name=Last_name
self.annual_salary=annual_salary
def give_raise(self,salary_raise=5000): #默认5000,但是想变的话实例输入就行
if salary_raise:
salary_raise=int(salary_raise)
self.annual_salary=self.annual_salary+salary_raise
#print(self.annual_salary)
#ah=Employee('zhang','san',10000)
#ah.give_raise(10000)
import unittest
class TestEmployee(unittest.TestCase):
def setUp(self):
self.ah=Employee('zhang','san',10000)
def test_give_default_raise(self):
self.ah.give_raise(5000)
self.assertEqual(self.ah.annual_salary,15000)
def test_give_custom_raise(self):
self.ah.give_raise(20000)
self.assertEqual(self.ah.annual_salary,30000)
unittest.main()