2.3.1 修改字符串大小写
变量名.title() #单词首字母大写
变量名.upper() #全部大写
变量名.lower() #全部小写
2.3.2 在字符串中使用变量(format)
变量A =f’{变量B} {变量C}’ #合并两个变量,f是设置格式的意思 #适用python3.6以上
变量A=‘{}{}’.format(变量B,变量C) #适用于python3.5及以前版本
2.3.3 制表符制作空白
\t #空格
\n #换行
2.3.4 删除空白
变量名.rstrip() #删除末尾多余的空白
变量名.lstrip() #剔除开头空格
变量名.strip() #剔除字符串两边空白
作业:
练习2-3 个性化消息
name = 'Eric'
message = f'Hello {name},would you like to learn some Python today?'
print(message)
练习2-4 调整名字大小写
name='mary'
print(name.title())
print(name.lower())
print(name.upper())
练习2-5 名言
name='TLi Jiacheng'
words='"If a man is weak, he is his greatest enemy."'
text=f'{name} once said,{words}'
print(text)
练习2-6 名言2
famous_person='TLi Jiacheng'
words='"If a man is weak, he is his greatest enemy."'
message=f'{famous_person} once said,{words}'
print(message)
#上一题的时候已经用过这个写法了
练习2-7 剔除人名中的空白
name=' mary \t \n'
print(name)
print(name.lstrip()) #只去除句子前的空白
print(name.rstrip()) #只去除句子后的空白
print(name.strip()) #前后都去除
2.4.2浮点数(带小数点的数)
注意:小数点可能不是不确定的;
2.4.3整数与浮点数
注意:
任意两数相除,结果总是浮点数。
其他运算若包含浮点数,结果必为浮点数。
2.4.5 同时给多个变量赋值
x,y,z=0,0,0 #xyz都初始化为0
2.4.6 常量
类似变量,但在程序中保持不变。通常用全 大写来表示。
作业:
2-8 数字8
print(4+4)
print(10-2)
print(2*2*2)
print(64/8)
2-9 最喜欢的数
x=0
print(‘我最喜欢的数是’,x)
2.5注释
作业:
2-10 添加注释
#没啥好注释的
print(‘hello world!’)
3.1.1 访问列表元素
list =[0,1,2...]
list[1]
print(list[0].title()) #找到某个位置的元素,使其首字母大写
3.1.3 使用列表中的各个值
作业:
3-1 姓名
friendsname=['mike','july','ben','emily']
print(friendsname[0],friendsname[1],friendsname[2],friendsname[3])
3-2 问候语
friendsname=['mike','july','ben','emily']
message = 'hello,my friend '
print (message +friendsname[0])
print (message +friendsname[1])
print (message +friendsname[2])
print (message +friendsname[3])
3-3 自己的列表
wayschool=['bike','bus','car','subway']
line= 'I would like to own a '
print (line +wayschool[0])
print (line +wayschool[1])
print (line +wayschool[2])
print (line +wayschool[3])
3.2.2 在列表中添加元素
list.append('x') #在列表末尾添加元素
list.insert(0,‘x’) #在列表任何位置添加元素,格式为insert(位置,内容)
3.2.3 从列表中删除元素
del list[0] #删除某位置的元素
list.pop() #弹出末尾值,赋值给变量后可以继续使用。pop默认末尾,也可以指定,格式pop(位置)
remove() #已知需要删除的值,将其移出列表。赋值后也可以继续使用。注意:只删除第一个指定的值。
作业:
3-4 嘉宾名单
list=['mom','dad','ray','lucy']
message=',if you are free tonight,please come to my house have dinner with me.'
number=0
while number<=3:
print(list[number],message)
number+=1
3-5 修改嘉宾名单
list=['mom','dad','ray','lucy']
message=',if you are free tonight,please come to my house have dinner with me.'
nocomelist='dad'
list.remove(nocomelist)
print(nocomelist,'does not make it')
list.append('ben')
number=0
while number<=3:
print(list[number],message)
number+=1
3-6 添加嘉宾
list=['mom','dad','ray','lucy']
message=',if you are free tonight,please come to my house have dinner with me.'
print('I find a big table,so I will invite more friends')
list.insert(0,'andrew')
list.insert(3,'emily')
list.append('ben')
number=0
while number<=6:
print(list[number],message)
number+=1
3-7 缩减名单
list=['mom','dad','ray','lucy']
message=',if you are free tonight,please come to my house have dinner with me.'
print('I find a big table,so I will invite more friends')
list.insert(0,'andrew')
list.insert(3,'emily')
list.append('ben')
number=0
while number<=6:
print(list[number],message)
number+=1
print('sorry,my table can not being there on time ,so i would like to invite two people come to my dinner')
i=0
while i <= 4:
byelist=list.pop()
print (byelist,',sorry,i cannot invite you')
i+=1
print(list[0],'remind you to come to my dinner tonight')
print(list[1],'remind you to come to my dinner tonight')
del list[0]
del list[0]
print(list)
3.3.1 使用方法sort()对列表永久排序
按字母顺序:list.sort()
按字母倒序:list.sort(reverse=True)
#sort是永久性变更,临时排序可用sorted(),例sorted(list,reverse=True)
3.3.3 倒着打印列表
按列表倒序:reverse()
#永久性,但可以再次reverse来恢复
3.3.4 确定列表的长度
len(list) #返回正常的计数
作业:
3-8 放眼世界
list=['beijing','xiamen','hongkong','south korea','canada']
print(list)
print(sorted(list))
print(list)
print(sorted(list,reverse=True))
list.reverse()
print(list)
list.reverse()
print(list)
list.sort()
print(list)
list.sort(reverse=True)
print(list)
3-9 晚餐嘉宾
list=['mom','dad','ray','lucy']
print('I invited',len(list),'guest')
3-10 尝试使用各个函数
list=['english','chinese','china','sundays','korea','book','king','time']
one=list.pop(0)
print(one)
list.insert(1,'way')
list.append('fine')
del list[0]
list.remove('time')
print(len(list))
list.sort()
list.reverse()
print(sorted(list,reverse=True))
3.4 使用列表时避免索引错误
索引从0开始,-1永远返回最后一位
#发生索引错误找不到原因时,打印列表长度看看
作业:
3-11 有意引发错误
list=[]
#print(list[-1]) #list index out of range
list.append('great')
print(list[-1])
4.1 遍历整个列表
times = ['one','two','three']
for time in times:
print(time)
#注意缩进、冒号等问题
作业:
4-1 比萨
pizzas=['Pepperoni Pizza','Barbeque Chicken Pizza','Hawaiian Pizza']
print(pizzas)
for pizza in pizzas:
print('I want to eat',pizza)
print('I really love pizza!')
4-2 动物
animals=['cat','dog','human']
for animal in animals:
print(animal)
for animal in animals:
print(animal,'would make a great pet')
print('any of these animals would make a great pet!')
4.3.1 使用函数range()
range(1,x) #实际包含的是 1~x-1的内容
range(1,x,y) x=范围,y=步长
4.3.3 对数字列表执行简单的统计计算
min(list),max(list),sum(list)
作业:
练习4-3 数到20
number =[value for value in range(1,21)]
print(number)
练习4-4 一百万
list=range(1,1000001)
for i in list:
print(i)
练习4-5 一百万求和
list=range(1,1000001)
print(min(list))
print(max(list))
print(sum(list))
练习4-6 奇数
list=range(1,21,2)
for i in list:
print(i)
练习4-7 3的倍数
list=range(3,31,3)
for i in list:
print(i)
练习4-8 立方
pfs=[]
for i in range(1,11):
pf =i**2
pfs.append(pf)
print(pf)
练习4-9 立方解析
pfs=[i**2 for i in range(1,11)]
print(pfs)
4.4.2 遍历切片
用切片不用赋值可以获得两个列表
作业:
练习4-10 切片
list=[1,2,3,4,5,6,7]
list2=list[:3]
print('the first three items in the list are:')
print(list2)
list3=list[2:5]
print('three items from the middle of the list are:')
print(list3)
list4=list[-3:]
print('the last three items in the list are:')
print(list4)
练习4-11 你的比萨,我的比萨
pizzas=['Pepperoni Pizza','Barbeque Chicken Pizza','Hawaiian Pizza']
new_pizzas=pizzas[:]
pizzas.append('onepizza')
new_pizzas.append('twopizza')
for pizza in pizzas:
print(pizza)
for pizza in new_pizzas:
print(pizza)
练习4-12 使用多个循环
my_foods =['pizza','falafel','carrot cake']
friend_foods =my_foods[:]
my_foods.append('ice cream')
friend_foods.append('cannoli')
print('my favorite foods are:')
for food in my_foods:
print(food)
print("my friend's favorite foods are: ")
for food in friend_foods:
print(food)
4.5.1 定义元组
touple=(n,m) #元组的关键在于“,”符号,如果元组只包含一个元素需要写为(n,)
4.5.3 修改元组变量
元组的元素不可以被修改,但元组本身可以重新赋值修改。#如果存储值值程序的整个生命周期都不变就使用元组。
例如:
dimensions=(200,50)时
dimensions[1]=100 是不行的
dismensions =(200,100)是可以的
作业:
练习4-13 自助餐
yzs=('sushi','sanwich','cake','pasta','fire chicken')
for yz in yzs:
print(yz)
yzs[0]='apple' #报错行
yzs=('sushi','sanwich','cake','salad','apple')
for yz in yzs :
print(yz)
练习4-14 pep 8
略
练习4-15 代码审核
#练习4-13的PEP8代码审核修改
yzs=('sushi','sanwich','cake','pasta','fire chicken')
for yz in yzs:
print(yz)
yzs[0]='apple' #报错行
yzs=('sushi','sanwich','cake','salad','apple')
for yz in yzs :
print(yz)
练习5-1 条件测试
name='mike'
print('Is name == "mike"?I predict True')
print('the anwser is--')
print(name == 'mike')
print('Is name == "jack"?I predict False')
print('the anwser is--')
print(name == 'jack')
print('Is name == "lucy"?I predict false')
print('the anwser is--')
print(name == 'lucy')
print('Is name == "andrew"?I predict False')
print('the anwser is--')
print(name == 'mike')
print('Is name == "andy"?I predict True')
print('the anwser is--')
print(name == 'andrew')
print('Is name == "andrew"?I predict False')
print('the anwser is--')
print(name == 'andy')
print('Is name == "july"?I predict False')
print('the anwser is--')
print(name == 'mike')
print('Is name == "july"?I predict Ture')
print('the anwser is--')
print(name == 'july')
print('Is name == "bob"?I predict False')
print('the anwser is--')
print(name == 'mike')
print('Is name == "sam"?I predict False')
print('the anwser is--')
print(name == 'mike')
练习 5-2 更多条件测试
#检查两个字符串相等和不等
a='1'
b='2'
c='2'
print('a==b是',a==b)
print('b==c是',b==c)
#使用方法lower()的测试
a_name='sum'
b_name='mike'
c_name='Sum'
print('a==b是',a_name.lower()==b_name.lower())
print('a==c是',a_name.lower()==c_name.lower())
#涉及相等、不等、大于、小于等于和小于等于的数值测试
a=1
b=1
c=2
d=3
print('a==b是',a==b)
print('a==c是',a==c)
print('a!=b是',a!=b)
print('a!=c是',a!=c)
print('a>b是',a>b)
print('c>a是',c>a)
print('a<b是',a<b)
print('a<c是',a<c)
print('a>=b是',a>=b)
print('a>=c是',a>=c)
print('a<=b是',a<=b)
print('c<=a是s',c<=a)
#使用关键字and和or的测试
a=1
b=1
c=2
print('a==b==c是',a==b and b==c)
print('a==b,b!=c是',a==b and b!=c)
#测试特定的值是否包含值列表中
list=[0,1,2,3,4]
print('1 in list是',1 in list)
print('5 in list是',5 in list)
#测试特定的值是否未包含值列表中
list=[0,1,2,3,4]
print('1 not in list是',1 not in list)
print('5 not in list是',5 not in list)
5.3.6 测试多个条件
只想执行一个代码块(只检查单个条件),就用if-elif-else结构,如果要执行多个代码块(多个条件并存,都需要检查),就使用一系列独立的if语句。
作业:
5-3 外星人颜色
alien_color='green'
if alien_color == 'green':
print('you got 5 point!')
if alien_color == 'yellow':
print('you got 20 point!')
5-4 外星人颜色2
#if版本
alien_color='green'
if alien_color == 'green':
print('you got 5 point!')
if alien_color != 'green':
print('you got 10 point!')
#else版本
alien_color='yellow'
if alien_color == 'green':
print('you got 5 point!')
else:
print('you got 20 point!')
5-5 外星人颜色3
alien_color='green'
if alien_color == 'green':
print('you got 5 point!')
elif alien_color == 'yellow':
print('you got 10 point!')
else:
print('you got 20 point!')
alien_color='yellow'
if alien_color == 'green':
print('you got 5 point!')
elif alien_color == 'yellow':
print('you got 10 point!')
else:
print('you got 20 point!')
alien_color='red'
if alien_color == 'green':
print('you got 5 point!')
elif alien_color == 'yellow':
print('you got 10 point!')
else:
print('you got 20 point!')
练习5-6 人生的不同阶段
age=19
age_type=''
if age<2:
age_type='婴儿'
elif age<4:
age_type='幼儿'
elif age<13:
age_type='儿童'
elif age<20:
age_type='青少年'
elif age<65:
age_type='成年人'
else:
age_type='老年人'
print('这个人是',age_type)
5-7 喜欢的水果
favorite_fruits=['bananas','apple','orange']
fruit = ''
if 'apple' in favorite_fruits:
fruit ='apple'
print('You really like',fruit)
if 'lemon'in favorite_fruits:
fruit ='lemon'
print('You really like',fruit)
if 'orange'in favorite_fruits:
fruit ='orange'
print('You really like',fruit)
if 'watermelon'in favorite_fruits:
fruit ='watermelon'
print('You really like',fruit)
if 'grape' in favorite_fruits:
fruit ='grape'
print('You really like',fruit)
5.4.2 确定列表不是空的
for循环时要检查列表是否为空,可以在else处对空表作处理。
作业:
练习5-8 以特殊方式和管理员打招呼
usernames=['admin','jack','ben','bob','lucy']
for username in usernames:
if username != 'admin':
print('Hello',username,'thank you for logging in again.')
else:
print('Hello admin,would you like to see a status report?')
练习5-9 处理没有用户的情形
usernames=['']
for username in usernames:
if username == '':
print('We need to find some users')
elif username != 'admin':
print('Hello',username,'thank you for logging in again.')
else:
print('Hello admin,would you like to see a status report?')
练习5-10 检查用户名
#创建新旧用户列表
Current_users=['Jaskson','jack','ben','bob','lucy']
new_users=['ben','lucy','mike','merry','gery']
#创建小写旧用户列表
current_users=Current_users[:]
for current_user in current_users:
current_user =current_user.lower()
#开始验证账号情况
for new_user in new_users:
if new_user.lower() in current_users:
print(new_user,'is being used')
else:
print(new_user,'is able to use')
5-11 序数
list=range(1,10)
for i in list:
if i == 1:
print(i,'st')
elif i == 2:
print(i,'nd')
elif i == 3:
print(i,'rd')
else:
print(i,'th')
练习5-12 设置if语句的格式
略
练习5-13 自己的想法
略
6.2 使用字典
格式:user_0={'x':'y','m':n}
6.2.1 访问字典中的值
格式:user_0['x']➡️y
6.2.2 添加键值对
格式:user_0['m']=n
6.2.4 修改字典中的值
赋值修改
6.2.5 删除键值对
格式:del user_0['x'] #删除的键值对会永久消失
6.2.7 使用get()来访问值
如果访问不存在的值会报错,所以需要方法get()来指定返回结果。
例如:
user_0 = {'color':'white','speed':'fast'}
point_value = user_0.get('points','No point value assigned.')
print(point_value)
#调用get()时,如果没指定第二个值,会直接返回None来表示没有这个值。
作业:
练习 6-1 人
person={'first_name':'ze','last_name':'kim','age':'19','city':'xiamen'}
print('first name is',person['first_name'])
print('last name is',person['last_name'])
print('age is',person['age'])
print('city is ',person['city'])
练习6-2 喜欢的数
like_numbers={}
like_numbers['mike']=1
like_numbers['bill']=11
like_numbers['lucy']=0
like_numbers['ferry']=9
like_numbers['jack']=100
print('mike likes',like_numbers['mike'])
print('bill likes',like_numbers['bill'])
print('lucy likes',like_numbers['lucy'])
print('ferry likes',like_numbers['ferry'])
print('jack likes',like_numbers['jack'])
练习 6-3 词汇表
dictionary={'变量':'能储存计算结果或能表示值的抽象概念',
'列表':'数据项构成的有限序列',
'字符串':'由数字、字母、下划线组成的一串字符',
'遍历':'遍历是指对树中所有结点的信息进行一次访问',
'缩进':'调整文本与页面边界之间的距离'}
print('变量:',dictionary['变量'])
print('列表:',dictionary['列表'])
print('字符串:',dictionary['字符串'])
print('遍历:',dictionary['遍历'])
print('缩进:',dictionary['缩进'])
6.3.1 遍历所有键值对
例子:
favorite_languages={
'jen':'python',
'phil':'python'
}
for name,language in favorite_languages.items():
print(name,"'s favorite language is",language)
6.3.3 按特定顺序遍历字典中的所有键
按顺序副本遍历
例:
for name in sorted(favorite_languages.key():
print(name,''thank you for taking the poll.")
6.3.4 遍历字典中的所有值
如果只需要返回值,剔除重复项。可以使用set。通过对包含重复元素的列表调用set()可以找出列表独一无二的元素,并用这些元素创建一个集合。
例如:
for language in set(favorite_languages.values()):
print(language.title())
#集合和字典容易混淆,都是用花括号定义。没有键值对的可能是集合,集合不以特定的顺序储存元素。
作业:
练习6-4 词汇表2
dictionary={'变量':'能储存计算结果或能表示值的抽象概念',
'列表':'数据项构成的有限序列',
'字符串':'由数字、字母、下划线组成的一串字符',
'遍历':'遍历是指对树中所有结点的信息进行一次访问',
'缩进':'调整文本与页面边界之间的距离'}
for name,text in dictionary.items():
print(f'{name.title()}是{text}') #这样写就没有多余的空格了
dictionary['字典']='字典是另一种可变容器模型,且可存储任意类型对象'
dictionary['循环']='迭代序列,即列表,元组,字典,集合或字符串'
dictionary['切片']='序列型对象的一种高级索引方法'
dictionary['集合']='用来保存不重复的元素的容器'
dictionary['键值对']='通过引用键来存储和检索元素的映射'
for name,text in dictionary.items():
print(f'{name.title()}是{text}')
练习6-5 河流
dictionary={'nile':'eegypt',
'Amazon River':'Brazil',
'Yangtze River':'China'}
for name,text in dictionary.items():
print(f'The {name.title()} runs through {text.title()}')
for name in dictionary.keys():
print(name)
for text in dictionary.values():
print(text)
练习6-6 调查
favorite_languages={
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python',
}
investagtions=['jen','emily','jack','phil']
for name in investagtions:
if name in favorite_languages.keys():
print(f'{name},thank you for help!')
else:
print(f'{name},please take our poll')
6.4 嵌套
将列表储存在字典中叫做嵌套。
6.4.3 在字典中存储字典
值可以对应多个
练习6-7 人们
person_0={'first_name':'ze','last_name':'kim','age':'19','city':'xiamen'}
person_1={'first_name':'eddy','last_name':'huang','age':'15','city':'taiwan'}
person_2={'first_name':'xiaoming','last_name':'wang','age':'7','city':'beijing'}
persons=[person_0,person_1,person_2]
for person in persons:
print('Name:',person['first_name'],person['last_name'])
print('Age:',person['age'])
print('City',person['city'])
练习6-8 宠物
pet_0={'name':'gigi','type':'pig','ower':'jack'}
pet_1={'name':'cherry','type':'dog','ower':'lucy'}
pet_2={'name':'kiki','type':'bird','ower':'mike'}
pets=[pet_0,pet_1,pet_2]
for pet in pets:
print('name:',pet['name'])
print('Type:',pet['type'])
print('ower:',pet['ower'])
print('')
练习6-9 喜欢的地方
favorite_places={}
favorite_places['mike']=['seaside','forest']
favorite_places['jack']=['shop','gym','home']
favorite_places['lucy']=['police station']
for name,places in favorite_places.items():
print(f"\n{name}'s favorites place are:")
for place in places :
print(f"\t{place}")
练习6-10 喜欢的数2
like_numbers={}
like_numbers['mike']=1,3,4
like_numbers['bill']=11,2
like_numbers['lucy']=0,1
like_numbers['ferry']=9,6,8,34
like_numbers['jack']=100,0
for name,numbers in like_numbers.items():
print(f"{name}'s favorites number are:")
for number in numbers:
print(f"{number}")
练习6-11 城市
cities={
'xiamen':{
'country':'china',
'population':'516w',
'fact':'Xiamen people speak Hokkien'
},
'sichuan':{
'country':'china',
'population':'8302w',
'fact':'Sichuan people like to eat spicy foods'
},
'taipei':{
'country':'china',
'population':'275w',
'fact':'Taipei prople use traditional characters'
}
}
for city_name,city_info in cities.items():
print(f'City name:{city_name}')
country=city_info['country']
population=city_info['population']
fact=city_info['fact']
print(f'Country:{country}')
print(f'Population:{population}')
print(f'Fact:{fact}')
print('')
练习6-12 拓展
#6.4.2 favorite_language.py 优化单数打印
favorite_languages = {
'jen':['python','ruby'],
'sarah':['c'],
'edward':['ruby','go'],
'phil':['python','haskell']
}
for name,languages in favorite_languages.items():
i = len(languages)
if i == 1:
print(f"\n{name.title()}'s favorite languages is:")
print(f"\t{language.title()}")
else:
print(f"\n{name.title()}'s favorite languages are:")
for language in languages:
print(f"\t{language.title()}")
7.1.2 使用int()来获取数值输入:
input默认输入字符串,如果要改为数字,需要int处理
如:a=int(a)s
7.1.3 求模运算符
求模运算符%,用于返回两数相除的余数结果。
作业:
练习7-1 汽车租赁
pre='Hello,welcome to our shop!'
pre+='what kind of car are you want?'
car=input(pre)
print(f"Let me see if I can find you a {car}")
练习7-2 餐馆订位
pre='Hello,welcome to our restaurant!'
pre+='How many people are coming for dinner?'
num=int(input(pre))
if num <=8 :
print("please follow me")
else:
print("I'm sorry, we don't have any tables available")
练习7-3 10的整倍数
pre='Hello,please enter a number here:'
num=int(input(pre))
if num %10 == 0 :
print(f"{num} is a multiple of 10.")
else:
print(f"{num} is not a multiple of 10.")
7.2.3 使用标志
定义一个变量,用于判断整个程序是否处于活动状态。(flag)
true时继续,false时候程序停止。
7.2.4 使用break退出循环
常用于for循环或者遍历
作业:
练习 7-4 比萨配料
tip='What do you want in your pizza?'
tip+='If you want to quit,enter "quit",please enter in here:'
while True:
thing = input(tip)
if thing == 'quit':
break
else:
print(f'we will add {thing} in your pizza')
练习 7-5 电影票
tips = 'How old are you? Please enter here:'
while True:
age = int(input(tips))
if age < 3:
print('Free')
elif age <= 12:
print('You should pay 10 dollars for tickle.')
else:
print('You should pay 15 dollars for tickle.')
练习 7-6 三种出路
#break写过了,就写一下7-4的while条件测试和变量active
#while条件测试
tip='What do you want in your pizza?'
tip+='If you want to quit,enter "quit",please enter in here:'
thing = '1'
while thing != 'quit':
thing = input(tip)
if thing == 'quit' :
print('---END---')
break
continue
print(f'we will add {thing} in your pizza')
#变量active
tip='What do you want in your pizza?'
tip+='If you want to quit,enter "quit",please enter in here:'
active = True
while active:
thing = input(tip)
if thing =='quit':
print('Finish')
active = False
else:
print(f'We will add {thing} in your pizza')
练习 7-7 无限循环
num=1
while num > 0:
print(num)
作业 7-8 熟食店
sandwich_orders=['Tuna Sandwich','Egg Sandwich','Turkey Sandwich']
finished_sandwiches=[]
while sandwich_orders:
made=sandwich_orders.pop()
print(f'I made your {made}.')
finished_sandwiches.append(made)
print('')
for finished_sandwich in finished_sandwiches:
print(finished_sandwich)
练习 7-9 五香烟熏牛肉卖完了
sandwich_orders=['Tuna Sandwich','pastrami','pastrami','Egg Sandwich','pastrami','Turkey Sandwich','pastrami']
while 'pastrami' in sandwich_orders:
sandwich_orders.remove('pastrami')
print('out of pastrami')
print(sandwich_orders)
练习7-10 梦想的度假胜地
promote_1='Enter "quit" to quit.'
promote_1+='What your name?Please enter here:'
promote_2='Enter "quit" to quit.'
promote_2+='If you could visit one place in the world,where would you go?,Please enter here:'
responses={}
active = True
while active :
name = input(promote_1)
if name == 'quit':
print('Finished')
active = False
place = input(promote_2)
if place == 'quit':
print('Finished')
active = False
else:
responses[name]=place
print(responses)
8.1 定义函数
格式示例:
def ab_c(x,y)
x=x+1
y=y+2
print(x,y)
ab_c(5,3)
8.1.2 实参和形参
如8.1示例,x,y是形参;5,3是实参。形参作为代号,实参参与实际的运算。
作业:
练习8-1 消息
def display_message():
print('We learn "def" in this class.')
display_message()
练习8-2 喜欢的图书
def favorite_book(title):
print(f'One of my favorite books is {title}.')
favorite_book('fresh off the boat')
8.2.1 位置实参
如8.1示例中,x和y分别对应5和3,就是位置的对应关系。此时如果位置写错,就可能造成结果出错。
8.2.2 关键字实参
指明关键字对应关系,相当于8.1的示例在调用时使用相反的顺序:ab_c(y=3,x=5)
但因为已经指定了形参,所以得出的结果仍然一致,不会报错。
8.2.3 默认值
编写函数时,可以给每个形参指定默认值,这样在没有实参的时候会自动使用默认值。
默认值格式:
def describe_pet(pet_name,animal_type='dog')
...
这样的话,不用指定animal_type,都会默认认为animal——type是dog。
如果需要指定,只需要在调用时指定animal_type即可。
作业:
练习 8-3 T恤
def make_shirt(size,line):
print(f'T-shirt size is {size} ,and there is a {line}on there')
make_shirt('s','Hello my friend!')
练习 8-4 大号T恤
def make_shirt(size,line='I Love Python.'):
print(f'T-shirt size is {size} ,and there is a "{line}" on there.')
make_shirt(size='XL')
make_shirt(size='M')
make_shirt(size='S',line='Hey')
练习 8-5 城市
def describe_city(ctname,ctcountry='China'):
print(f'{ctname} is in {ctcountry}.')
describe_city(ctname='sichuan')
describe_city(ctname='taiwan')
describe_city(ctname='newyork',ctcountry='America')
8.3 返回值
在函数中可以使用return语句将值返回到调用函数的代码行。
注:前面示例的函数都是在定义阶段设置了打印了,如果在函数内部不需要打印,而是需要储存这个信息,等待调用的时候再进行打印或其他数据处理,就需要用到return。
8.3.2 让实参变成可选的
在需要3个实参的时候,有可能部分的项目只有2个项目。在同一个函数中,为了保证函数可以正常运行,可以将其中1个实参变为可选项。使得用户没有提供可选实参时,默认不使用形参。文字格式时赋空值‘’,数字赋空值=None
格式:
def get_formatted_name(first_name,last_name,middle_name=''):#默认卸写在最后一位,赋空值
if middle_name:#存在,即有值时
full_name=f'{first_name} {middle_name} {last_name}'
else: #无值时
full_name = f'{first_name} {last_name}'
return full_name.title()
作业:
练习 8-6 城市名
def city_country(city_name,country_name):
print(f'"{city_name},{country_name}"')
city_country('SiChuan','China')
city_country('Tokyo','Japan')
city_country('Seoul','Korea')
练习8-7 专辑
def make_album(singer_name,album_name,songs_number=None):
if songs_number:
full_message={
'singer_name':singer_name,
'album_name':album_name,
'songs_number':songs_number
}
else:
full_message={
'singer_name':singer_name,
'album_name':album_name
}
return full_message
album=make_album('jack','one')
print(album)
album=make_album('nike','two',10)
print(album)
album=make_album('lucy','three',5)
print(album)
练习8-8 用户的专辑
def make_album(singer_name,album_name):
album_info={
'singer_name':singer_name,
'album_name':album_name
}
return album_info
while True:
print('Please enter the album information here:')
print('(Enter "q" to quit)')
s_name=input("Singer's name:")
if s_name == "q":
break
a_name=input("Album's name:")
if a_name == "q":
break
album=make_album(s_name,a_name)
print(album)
8.4.1 在函数中修改列表
每一个函数做一件事,效率会更高。复用性更好。
作业:
练习 8-9 消息
def show_messages(messages):
for i in messages:
print(i)
words=['Hello','GoodBye','Thankyou','Nice to meet you!']
show_messages(words)
练习 8-10 发送消息
def send_message(message,s_message):
while message:
sending = message.pop()
s_message.append(sending)
message=['Hello','GoodBye','Thankyou','Nice to meet you!']
s_message=[]
print(message)
print(s_message)
print('')
send_message(message,s_message)
print(message)
print(s_message)
练习 8-11 消息归档
def send_message(message,s_message):
while message:
sending = message.pop()
s_message.append(sending)
words=['Hello','GoodBye','Thankyou','Nice to meet you!']
s_words=[]
words_2=words[:]
send_message(words_2,s_words)
print(words_2)
print(words)
8.5 传递任意数量的实参
不知道需要传入的实参数量时,可以用*,使形参成为元组,将收到的值=封装值元组里。如果使用**,就创建一个字典。
格式:
def make_pizza(*toppings):
print(toppings)
注:任意数量实参必须放在最后。*args是通用形参名,收集任意数量的位置形参。**kwargs是形参名,用于收集任意数量的关键词实参。
作业:
练习 8-12 三明治
def sandwich_inside(sanwich_kind,*foods):
print(f'{sanwich_kind} has:' )
for food in foods:
print(food)
sandwich_inside('egg sanwich','bread','egg')
print('')
sandwich_inside('non_sandwich','nothing')
print('')
sandwich_inside('great_sandwich','meat','egg','tomato','fish')
练习 8-13 用户简介
def build_profile(first,last,**user_info):
user_info['first_name']=first
user_info['last_name']=last
return user_info
user_profile =build_profile('CW',
'Deng',
location='XiaMen',
field='Game',
interest='read'
)
print(user_profile)
练习8-14 汽车
def car_type(brand,model,**other_info):
other_info['car_brand']=brand
other_info['car_model']=model
return other_info
car=car_type('subaru','001', color='white',two_package='True')
print(car)
8.6.1 导入整个模块
同文件夹下,import命令。
from 模块 import 函数(“import*”表示导入整个模块所有函数)
8.6.3 使用as给函数指定别名
from 模块 import 函数 as xxxx(自己指定的名字,之后的调用直接用指定名)
注:模块也可以指定别名,操作方法一样
作业:
练习 8-15 打印模型
#准备被调用的函数 printing_functions.py
def printing_way(unprinted_designs,completed_models):
while unprinted_designs:
current_design = unprinted_designs.pop()
print(f'printing model:{current_design}')
completed_models.append(current_design)
print('The following models have been printed:')
for completed_model in completed_models:
print(completed_model)
#调用其他程序的主程序 printing_models.py
from printing_functions import*
unprinted_designs=['phone case','robot pendant','dodecahedron']
completed_models=[]
printing_way(unprinted_designs,completed_models)
两个代码放在同一个文件夹下,然后运行后者printing_models.py
练习 8-16 导入
(没法写出来)略
练习8-17 函数编写指南
(基本上好像都没问题)略
9.1 创建和使用类
示例:
class xx:
def __init__(self,xx,yy) #self是必须的
作业:
练习 9-1 餐馆
class Restaurant:
def __init__(self,restaurant_name,cuisine_type):
self.name=restaurant_name
self.type=cuisine_type
def describe_restaurant(self):
print(f'{self.name} is a {self.type} restaurant.')
def open_restaurant(self):
print(f'{self.name} is open now.')
restaurant=Restaurant('sorry no sorry','Chinese food')
restaurant.describe_restaurant()
restaurant.open_restaurant()
练习 9-2 三家餐馆
class Restaurant:
def __init__(self,restaurant_name,cuisine_type):
self.name=restaurant_name
self.type=cuisine_type
def describe_restaurant(self):
print(f'{self.name} is a {self.type} restaurant.')
def open_restaurant(self):
print(f'{self.name} is open now.')
restaurant_0=Restaurant('sorry no sorry','Chinese food')
restaurant_1=Restaurant('hungry bird','fast food')
restaurant_2=Restaurant('sisiki','Japenese food')
restaurant_0.describe_restaurant()
restaurant_1.describe_restaurant()
restaurant_2.describe_restaurant()
练习 9-3 用户
class User:
def __init__(self,first_name,last_name,user_info):
self.first=first_name
self.last=last_name
self.info=user_info
def describe_user(self):
print(f'{self.first} {self.last} is a {self.info}')
def greet(self):
print(f'Hello,{self.first} {self.last}.')
user_0=User('ming','lee','admin')
user_1=User('mike','frank','guest')
user_2=User('shine','lu','guest')
user_0.describe_user()
user_0.greet()
user_1.describe_user()
user_1.greet()
user_2.describe_user()
user_2.greet()
9.2.2 给属性指定默认值
在def__init__(self,xxxxx)内直接赋值为0即可指定默认值
9.2.3 修改属性的值
直接改:赋予实例类属性后,可直接针对该实例进行赋值。例:实例.原代称=xx
用方法改:类内部设计一个函数针对值进行更新。如果要设计成不回退,可以加if/else条件语句。
作业:
练习 9-4 就餐人数
class Restaurant:
def __init__(self,restaurant_name,cuisine_type):
self.name=restaurant_name
self.type=cuisine_type
self.number_served=0
def describe_restaurant(self):
print(f'{self.name} is a {self.type} restaurant.')
def open_restaurant(self):
print(f'{self.name} is open now.')
def read_number_served(self):
print(f'{self.number_served} people are eating now.')
def set_number_served(self,set_number):
self.number_served = set_number
def increment_number_served(self,increment_number):
self.number_served += increment_number
res_1=Restaurant('sorry no sorry','Chinese food')
res_1.read_number_served()
res_1.set_number_served(5)
res_1.read_number_served()
res_1.increment_number_served(100)
res_1.read_number_served()
练习9-5 尝试登陆次数
class User:
def __init__(self,first_name,last_name,user_info):
self.first=first_name
self.last=last_name
self.info=user_info
self.login_attempts=0
def describe_user(self):
print(f'{self.first} {self.last} is a {self.info}')
def greet(self):
print(f'Hello,{self.first} {self.last}.')
def read_login_attempts(self):
print(f'attempts to login {self.login_attempts} times.')
def increment_login_attempts(self):
self.login_attempts+=1
def reset_login_attempts(self):
self.login_attempts=0
user_0=User('ming','lee','admin')
user_0.read_login_attempts()
user_0.increment_login_attempts()
user_0.increment_login_attempts()
user_0.increment_login_attempts()
user_0.read_login_attempts()
user_0.reset_login_attempts()
user_0.read_login_attempts()
9.3.1 子类的方法__init__()
子类可以继承父类方法中定义的属性(父类需要在同一个文件中,且在子类前面才可以用)
使用方法是:
class 子类(父类名):
def __init__(xxx) #先正常定义自己,再在后面继承
super().__init__(xxxx) #除了super().之外去掉self,其余和父类方法定义行一样。
9.3.3 重写父类的方法
子类内直接重新def即可。之后调用都用子类方法。
9.3.4 将实例用作属性
把类变成方法:假设有一个类可以放在另一个类中。可在定义/继承行后面使用self.xxx=原类名(),调用的时候需要多写一个xxx(定义名)如:user_01.xxx.原类下方法()
作业:
练习 9-6 冰淇淋小店
class Restaurant:
def __init__(self,restaurant_name,cuisine_type):
self.name=restaurant_name
self.type=cuisine_type
self.number_served=0
def describe_restaurant(self):
print(f'{self.name} is a {self.type} restaurant.')
def open_restaurant(self):
print(f'{self.name} is open now.')
def read_number_served(self):
print(f'{self.number_served} people are eating now.')
def set_number_served(self,set_number):
self.number_served = set_number
def increment_number_served(self,increment_number):
self.number_served += increment_number
class IceCreamStand(Restaurant):
def __init__(self,restaurant_name,cuisine_type):
super().__init__(restaurant_name,cuisine_type)
self.flavors=['starwbarry','pemiry','coffee']
def show_icecream(self):
print(f'flavors:{self.flavors}')
res_1=IceCreamStand('sorry no sorry','Chinese food')
res_1.show_icecream()
练习 9-7 管理员
class User:
def __init__(self,first_name,last_name,user_info):
self.first=first_name
self.last=last_name
self.info=user_info
self.login_attempts=0
def describe_user(self):
print(f'{self.first} {self.last} is a {self.info}')
def greet(self):
print(f'Hello,{self.first} {self.last}.')
def read_login_attempts(self):
print(f'attempts to login {self.login_attempts} times.')
def increment_login_attempts(self):
self.login_attempts+=1
def reset_login_attempts(self):
self.login_attempts=0
class Admin(User):
def __init__(self,first_name,last_name,user_info):
super().__init__(first_name,last_name,user_info)
self.privileges=['can ban user','can add post','can delete post']
def show_pribileges(self):
print(f"Admin's privileges:{self.privileges}")
user_0=Admin('ming','lee','admin')
user_0.show_pribileges()
练习9-8 权限
class User:
def __init__(self,first_name,last_name,user_info):
self.first=first_name
self.last=last_name
self.info=user_info
self.login_attempts=0
def describe_user(self):
print(f'{self.first} {self.last} is a {self.info}')
def greet(self):
print(f'Hello,{self.first} {self.last}.')
def read_login_attempts(self):
print(f'attempts to login {self.login_attempts} times.')
def increment_login_attempts(self):
self.login_attempts+=1
def reset_login_attempts(self):
self.login_attempts=0
class Pribileges:
def __init__(self):
self.privileges=['can ban user','can add post','can delete post']
def show_pribileges(self):
print(f"Admin's privileges:{self.privileges}")
class Admin(User):
def __init__(self,first_name,last_name,user_info):
super().__init__(first_name,last_name,user_info)
self.pribileges=Pribileges()
def show_pribileges(self):
print(f"Admin's privileges:{self.privileges}")
user_0=Admin('ming','lee','admin')
user_0.pribileges.show_pribileges()
练习9-9 电瓶升级
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 = f"{self.year}{self.make}{self.model}"
return long_name.title()
def read_odometer(self):
print(f"This car has {self.odometer_reading} miles on it.")
def update_oddmeter(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 Battery:
def __init__(self,battery_size=75):
self.battery_size = battery_size
def get_range(self):
if self.battery_size == 75:
range = 260
elif self.battery_size == 100:
range = 315
print(f"This car can fo about {range} mile on a full charge.")
def upgrade_battery(self):
if self.battery_size != 100:
self.battery_size +=25
class ElectricCar(Car):
def __init__(self,make,model,year):
super().__init__(make,model,year)
self.battery = Battery()
car_01=ElectricCar('tesla','A02','2009')
car_01.battery.get_range()
car_01.battery.upgrade_battery()
car_01.battery.get_range()
练习 9-10 导入Restaurant类
略
练习 9-11 导入Admin类
略
练习 9-12 多个模块
略
练习 9-13 骰子
from random import randint
class Die :
def __init__(self,times,side):
self.times=times
self.side=side=6
def roll_die(self,side):
side = randint(1,side)
print(f'You roll:{side}')
def roll_times(self,times,side):
self.times = times
self.side=side
i=0
while i < times:
self.roll_die(side)
i+=1
#6面丢一次
fri_round=Die(10,6)
fri_round.roll_times(1,6)
#6面丢十次
twe_round=Die(10,6)
twe_round.roll_times(10,6)
#10面丢十次
thr_round=Die(10,10)
thr_round.roll_times(10,10)
#20面丢十次
thr_round=Die(10,20)
thr_round.roll_times(10,20)
练习 9-14 彩票
from random import choice
hold_list=['19','13','86','55','9','17','0','70','27','54','f','p','q','i','j']
award_list=[]
time=4
while time > 0:
award_one=choice(hold_list)
hold_list.remove(award_one)
#这一步原先用了pop方法报错了,原因是pop()需要内的是索引值
award_list.append(award_one)
time-=1
print(f'{award_list},IF you have this four sign,you got the big award!')
练习9-15 彩票分析
from random import choice
award_list=['13','27','i','j']
award_list.sort()
print(f'The award numbers is {award_list}')
print(f'IF you have this four sign,you got the big award!')
my_list=[]
def buy_tickle():
global my_list #声明该变量是全局变量,使得其可以在函数外使用
#每次抽奖前置空我的选择,并把所有选择展出出来
my_list=[]
hold_list=['19','13','86','55','9','17','0','70','27','54','f','p','q','i','j']
#获取一组含有4个元素的奖票
i=4
while i > 0:
get_one=choice(hold_list)
hold_list.remove(get_one)
my_list.append(get_one)
i=i-1
my_list.sort()
return my_list
#初始化抽奖次数
buy_count=1
buy_tickle()
while my_list != award_list:
#未中奖时持续抽奖
buy_tickle()
buy_count+=1
if my_list == award_list:
print('you got it!')
break
print(f'You try {buy_count} times.')
#因为没有使用全局变量绕了一个大圈,检查了几个小时都找不到报错的原因
练习9-16 Python Module of the Week
略
10.1 从文件中读取数据
格式:
with open('路径/文件名.后缀') as #没指定路径默认访问当前文件的文件夹
file_object:
contents = file_object.read()
print(contents.retrip()) #read默认多打印一个空行,使用rstrip去除它
作业:
练习 10-1 Python学习笔记
with open('learning_python.txt')as file_object:
contents=file_object.read()
print(contents)
with open('learning_python.txt')as file_object:
for line in file_object:
print(line)
with open('learning_python.txt')as file_object:
lines=file_object.readlines()
for line in lines :
print(line)
练习 10-2 C语言学习笔记
with open('learning_python.txt')as file_object:
for line in file_object:
message=line.replace('Python','C')
print(message)
10.2.1 写入空文件
要将文本写入文件,调用open()时需要提供另一个实参
例:
filename = 'programming.txt'
with open(filename,'w')as file_object:
file_object.write('I love programming.')
#读取模式('r')、写入模式('w')、附加模式('a')或读写模式('r+'),没写默认只读。如果要写入的文件不存在,函数open()将自动创建一个。
作业:
练习10-3 访客
promote='please enter your name:'
username=input(promote)
file_name='guest.txt'
with open (file_name,'a') as file_object:
file_object.write(f'{username}\n')
练习10-4 访客名单
promote=('please enter your name here:')
promote+=("(enter 'q' to quit)")
while True:
username=input(promote)
if username == 'q':
break
else:
print(f'hello,{username},nice to meet you.')
file_name='guest_book.txt'
with open (file_name,'a') as file_object:
file_object.write(f'{username}\n')
练习10-5 调查
promote=('why you like coding:')
promote+=("(enter 'q' to quit)")
while True:
reason=input(promote)
if reason == 'q':
break
else:
file_name='coding_reasons.txt'
with open (file_name,'a') as file_object:
file_object.write(f'{reason}\n')
10.3.2 使用try-except代码块
用处:包装报错让用户更容易理解
例:
try:
print(5/0)
except ZeroDivisionError:
print("You can't divide by zero! ")
#通常将引发报错的代码放在try,else后执行正确代码
10.3.8 静默失败
上述的try-except用法不打印而选择pass就会跳过
作业:
练习10-6 加法运算
promote=('Enter two number,and I will add two of them.')
promote+=('please enter the frist number:')
promote_2=('please enter the second number:')
try :
num_1=int(input(promote))
except ValueError:
print("You're not entering a number!")
else:
try :
num_2=int(input(promote_2))
except ValueError:
print("You're not entering a number!")
else:
anwser=num_1+num_2
print(f'{num_1}+{num_2}={anwser}')
练习10-7 加法计算器
def add_two():
promote=('Enter two number,and I will add two of them.')
promote+=('please enter the frist number:')
promote_2=('please enter the second number:')
try :
num_1=int(input(promote))
except ValueError:
print("You're not entering a number!")
else:
try :
num_2=int(input(promote_2))
except ValueError:
print("You're not entering a number!")
else:
anwser=num_1+num_2
print(f'{num_1}+{num_2}={anwser}')
while True:
add_two()
练习10-8 猫和狗
file_names=['cats.txt','dogs.txt']
for file_name in file_names:
try:
with open(file_name)as file_object:
content = file_object.read()
except FileNotFoundError:#别漏写了Error
print(f'Can not found {file_name}.')
else:
with open(file_name)as file_object:
for line in file_object:
print(line.rstrip())
练习10-9 静默的猫和狗
file_names=['cats.txt','dogs.txt']
for file_name in file_names:
try:
with open(file_name)as file_object:
content = file_object.read()
except FileNotFoundError:#别漏写了Error
pass
else:
with open(file_name)as file_object:
for line in file_object:
print(line.rstrip())
练习10-10 常见单词
file_name='book.txt'
times=0
times_1=0
times_2=0
with open(file_name) as file_object:
for line in file_object:
times=line.lower().count('the')
times_1+=times
print(f"'the' shows up {times_1} times.")
with open(file_name) as file_object:
for line in file_object:
times=line.lower().count('the ')
times_2+=times
print(f"'the ' shows up {times_2} times.")
10.4 存储数据
模块json让你能够将简单的Python数据结构转储到文件中,并在程序再次运行时加载该文件中的数据。JSON(JavaScript Object Notation)
10.4.1 使用json.dump()和json.load()
json.dump(要存的数据,用于存储数据的文件对象)
变量=json.load(用于存储数据的文件对象)
作业:
练习10-11 喜欢的数
import json
file_name='f_n.json'
favorite_number=input('please enter your favorite number:')
with open(file_name,'w')as file_object:
json.dump(favorite_number,file_object)
with open(file_name,'r')as file_object:
number=json.load(file_object)
print(f"I know your favorite number! It's {number}.")
练习10-12 记住喜欢的数
import json
filename = 'favorite_number.json'
def get_stored_number():
try:
with open(filename)as f:
number=json.load(f)
except FileNotFoundError:
return None
else:
return number
def get_new_number():
number=input("What is your favorite number?")
with open(filename,'w')as f:
json.dump(number,f)
return number
def answer_user():
number = get_stored_number()
if number:
print(f"You favorite number is,{number}!")
else:
number=get_new_number()
print("I will remember your favorite numbers.")
answer_user()
练习10-13 验证用户
import json
filename = 'username.json'
def get_stored_username():
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?")
with open(filename,'w')as f:
json.dump(username,f)
return username
def greet_user():
username = get_stored_username()
if username:
confirm=input(f"If you're {username},please enter 'y' to confirm.")
if confirm == 'y':
print(f"Welcome back ,{username}!")
else:
username=get_new_username()
print(f"We'll remember you when you come back,{username}!")
else:
username=get_new_username()
print(f"We'll remember you when you come back,{username}!")
greet_user()
11.1.2 可通过的测试
要为函数编写测试用例,可先导入模块unittest和要测试的函数,再创建一个继承unittest.TestCase的类,并编写一系列方法对函数行为的不同方面进行测试。
参考:(目前不是很理解,以后再重看)
import unittest
for name_function import get_formatted_name
class NameTestCase(unittest.TestCase):
def test_first_last_name(self):
formatted_name = get_formatted_name('janis','joplin')
self.assertEqual(formatted_name,'Janis Joplin')
if __name__=='__main__':
unittest.main()
作业:
练习11-1 城市和国家
#被测试函数部分 city_functions.py
def city_country(city,country):
conbind=city+','+country
return conbind
#测试函数部分 test_cities.py
import unittest
from city_functions import city_country
class NameTestCase(unittest.TestCase):
def test_first_last_name(self):
conbind = city_country('santiago','chile')
self.assertEqual(conbind,'santiago,chile')
if __name__=='__main__':
unittest.main()
练习11-2 人口数量
#city_function.py
def city_country(city,country,population):
conbind=city+','+country+'-'+population
return conbind
#test_cities.py
import unittest
from city_functions import city_country
class NameTestCase(unittest.TestCase):
def test_first_last_name(self):
conbind = city_country('santiago','chile')
self.assertEqual(conbind,'santiago,chile-')
if __name__=='__main__':
unittest.main()
11.2.1 各种断言方法
unittest模块中的断言方法
方法 | 用途 |
assertEqual(a,b) | 核实a==b |
assertNotEqual(a,b) | 核实a!=b |
assertTrue(x) | 核实x为True |
assertFalse(x) | 核实x为False |
assertIn(item,list) | 核实item在list中 |
assertNotIn(item,list) | 核实item不在list中 |
作业:
练习11-3 雇员 (一直报错看了3个小时都看不出来问题,先挂着,日后弄懂了测试再解)
#被调用的 employee.py
class Employee:
def __init__(self,fristname,lastname,pay):
self.fristname = fristname
self.lastname = lastname
self.pay = pay
def give_raise(self,pay_raise=5000):
self.pay_raise=pay_raise
self.pay+=pay_raise
#测试.py
import unittest
from employee import *
class TestEmployee(unittest.TestCase):
def setUp(self):
self.employee=Employee('wang','ming',3000)
def test_give_default_raise(self):
self.employee.give_raise()
self.assertNotEqual(self.pay,9000)
def test_give_custom_raise(self):
self.employee.give_raise()
self.assertEqual(self.pay,8000)
if __name__ =='__main__':
unittest.main()
#测试.py 报错:AttributeError: 'TestEmployee' object has no attribute 'pay'
#暂时不明白,日后再看