Python学习笔记

  • 基础知识
  • 第1章 变量和简单数据类型
  • 1.1 变量
  • 1.1.1 变量的命名和使用
  • 1.1.2 输出/输入
  • 1.2 字符串
  • 1.2.1 使用方法修改字符串的大小写
  • 1.2.2 合并(拼接)字符串
  • 1.2.3 字符串相关操作
  • 1.2.4 删除空白
  • 1.2.5 常见操作
  • 1.3 数字
  • 1.3.1 整数、浮点数、布尔值
  • 1.3.2 运算符
  • 第2章 列表
  • 2.1 列表表示与访问
  • 2.2 列表的相关操作
  • 2.2.1 增、删、改,查操作
  • 2.2.2 列表排序、反转、长度获取
  • 2.3 列表嵌套(遍历、创建)
  • 2.3.1 遍历列表
  • 2.3.2 创建数值列表
  • 2.3.2 最大值、最小值、总和
  • 2.3.3 列表解析
  • 2.4 使用列表的一部分
  • 2.4.1 切片
  • 2.4.2 遍历切片
  • 2.4.3 复制列表
  • 2.5 练习
  • 8个老师随机放入三个办公室中
  • 购物车
  • 第3章 元组
  • 3.1 元组介绍
  • 第4章 if语句
  • 4.1 条件测试
  • 4.2 if-elif-else语句
  • 4.4 多个elif语句
  • 4.5 省略else代码块
  • 第5章 字典
  • 5.1 使用字典
  • 5.2 增、删、改
  • 5.3 遍历(查)字典
  • 5.4 嵌套
  • 5.4.1 字典列表
  • 5.4.2 字典中存储列表
  • 5.4.3 在字典中存储字典
  • 5.4.4 字典枚举
  • 字典、列表、元组、集合
  • 第6章 用户输入与循环
  • 6.1用户输入intput()
  • 6.2 while循环
  • 6.3 while循环处理列表和字典
  • 6.3.1 在列表间移动数据
  • 6.3.2 删除包含特定值的所有列表元素
  • 6.3.3 使用用户输入来填充字典
  • 6.4 for...in...
  • 第7章 函数
  • 7.1 定义函数
  • 7.2 传递实参
  • 7.3 返回值
  • 7.4 传递列表
  • 7.5 传递任意数量的实参
  • 7.6 将函数存储在模块中
  • 7.7 lambda函数
  • 第8章 类
  • 8.1 创建和使用类
  • 8.2 使用类和实例
  • 8.3 继承
  • 8.3.1 子类的方法__init__()
  • 8.3.2给子类定义属性和方法
  • 8.3.3重写父类的方法
  • 8.3.4将实例用作属性
  • 8.4 导入类
  • 第9章 文件和异常
  • 9.1 从文件中读取数据
  • 9.1.1 打开与关闭整个文件
  • 9.1.2 文件读取
  • 9.1.3 使用文件的内容
  • 9.2 写入文件
  • 9.3 文件的相关操作
  • 9.4 异常
  • 9.5 存储数据
  • 9.5.1 重构
  • 第10章 测试代码
  • 10.1 测试类



声明:B站所看视频链接以及python书籍内容,自己仅作为自己学习笔记记录,不作为其他用途


链接:

https://www.bilibili.com/video/BV1rg411G7mp?from=search&seid=3903997370168689438&spm_id_from=333.337.0.0. python结合医学


书籍:《Python编程 从入门到实践》

基础知识

第1章 变量和简单数据类型

1.1 变量

1.1.1 变量的命名和使用

命名规则:

  • 字母、数字和下划线,但不能以数字开头;
  • 变量不能含空格,可以以下划线间隔;
  • 不要将Python关键字和函数名用作变量名;
  • global 变量名声明全局变量在函数中的标识符

type(变量名) 查数据类型

message = "Hello world!"
print(message)
message = "变量练习"
print(message)
print(type(message))   #<class 'str'>
1.1.2 输出/输入
  • sep = ‘’,end = ‘’
  • input() #默认字符串,提示信息,接受的必须是表达式
# -*- codeing = utf-8 -*-
# @Time:2022/5/48:23
# @Author:yugan
# @File:demo1.py
# @Software:PyCharm

#格式化输出
print("我叫%s,来自%s"%("鱼干","中国"))
#我叫鱼干,来自中国

age = 18
print("我今年%d岁"%age)
#我今年18岁

print('aaa','bbb','ccc')
#aaa bbb ccc

print('www','baidu','com',sep='.')#sep分隔
#www.baidu.com

print('helllo',end='')#end=''表示不换行
print('world',end='\t')
print('Python',end='\n')
print('end')
#hellloworld	Python
#end

#输入
password = input("请输入密码:")
print("您刚刚输入的密码是:",password)
#请输入密码:123456
#您刚刚输入的密码是: 123456

1.2 字符串

用引号括起得都是字符串,引号可以使单引号也可以是双引号

  • 区间索引[A:B:n]
  • 从位置A到B的部分字符串,不包含位置B
  • A起始位置,B结束位置,n步长
1.2.1 使用方法修改字符串的大小写

方法名

作用

变量名.title()

以首字母大写的方式显示每个单词

变量名.upper()

字符串全部大写

变量名.lower()

字符串全部小写

name = "my name is python"
print(name.title())#My Name Is Python
print(name.upper())#MY NAME IS PYTHON
print(name.lower())#my name is python
1.2.2 合并(拼接)字符串

‘+’连接

name = "Python"
print("Hello" + " " + name + "!")
1.2.3 字符串相关操作
  • 字符串分割 :string.split()
  • 字符串格式化输出 :使用{}占位string.format()
  • 如:‘{}公斤{}厘米’.format(70,175)

符号

作用

\n

换行

\t

制表符(空格)

\

转义(\后引号正常输出)

\r

光标移动到一行的开始

|反斜杠

r"字符串内容"

防止字符转义

‘’’ ‘’’

允许字符跨多行

print("I'm a student")
print('I\'m a student')
print(r"I'm a student")
1.2.4 删除空白

方法名

作用

变量名.rstrip()

字符串末尾没有空白

变量名.lstrip()

字符串开头没有空白

变量名.strip()

字符串两端没有空白

1.2.5 常见操作

名称

描述

isalnum()

字符串至少有一个字符并且所有字符都是字母或数字则返回True,否则返回False

isalpha()

字符串至少有一个字符并且所有字符都是字母则返回True,否则返回False

isdigit()

字符串只包含数字则返回True,否则返回False

isnumeric()

字符串只包含数字字符则返回True,否则返回False

join(seq)

以指定字符串作为分隔符,将seq中所有的元素合并为一个新的字符串

len(string)

返回字符串长度

split(str=“”,num=string.count(str))num=string.count(str))

以str为分隔符截取字符串,如果num有指定值,则仅截取num+1个字符串

1.3 数字

1.3.1 整数、浮点数、布尔值

整数:
浮点数:
布尔值:false相当于0,true相当于1

  • 类型转换
  • 整数->浮点数 float(4)->4.0
  • 浮点数->整数 int(3.14)->3
  • 字符串->整数,浮点数 int(‘3’)->3,float(‘3.14’)->3.14
1.3.2 运算符

类别

运算符

含义

算术

/

结果为浮点数


//

整除


%

取余


**

幂运算/次方运算

赋值

+=


-=


*=


/=


%=


**=


//=

比较

==

相等


!=


>=


<=

比较运算符返回结果为false或true

位运算符

&

与:相同为1不同为0


1

或:有1为1


^

异或:不同为1


~

取反:1为0,0为1


<<

左移:高位丢弃,低位补0


>>

右移:

第2章 列表

2.1 列表表示与访问

#列表的表示
liebiao = ['alice',23,50.8,120,90,65]
print(liebiao)
#访问列表元素
print(liebiao[0].title())
#访问最后一个元素用索引-1
print(liebiao[-1])

2.2 列表的相关操作

列表操作符

含义

list1+list2

合并(连接)两个列表

list1*n

重复n次列表内容

len(list1)

返回列表长度(元素个数)

x in list1

检查元素是否在列表中

2.2.1 增、删、改,查操作

方法

含义

列表名[索引号] = 元素

修改元素/替换

列表名.append(元素)

列表末尾添加元素

列表名.extend(列表名)

列表的追加(拆散加入)

列表名.insert(索引号,元素)

插入元素

del 列表名[索引号]

删除指定位置元素

列表名.pop()

删除列表末尾元素,但是依旧可以使用

列表名.pop(索引号)

弹出列表中任何位置的元素

列表名.remove(元素)

删除指定元素(依旧可以使用,重复内容只删一个)

in ,not in

在/不在

列表名.index(‘元素’,起始下标,终止下标)

查找指定下标范围的元素,并返回找到对应元素的下标(区间左闭右开),找不到会报错

列表名.count(‘元素’)

统计指定元素出现几次

# append与extend的区别
a = [1,2]
b = [3,4]
c = [5,6]
a.append(b)
print(a)    #[1, 2, [3, 4]]
a.extend(c)
print(a)    #[1, 2, [3, 4], 5, 6]

#删del、pop、remove
namelist = ['小红','小王','小兰','鱼干']
#del namelist[0]   #小王  小兰  鱼干
#namelist.pop()    #小红 小王 小兰
namelist.remove("鱼干")    #小红 小王 小兰
for name in namelist:
    print(name)
#pop
liebiao = ['alice',23,50.8,120,90,65]
popliebiao = liebiao.pop(0)
print(liebiao)  #[23, 50.8, 120, 90, 65]
print(popliebiao)  #alice

#查 in  not in
namelist = ['小红','小王','小兰','鱼干']
findname = input("请输入查找名字:")
if findname in namelist:
    print("存在")
else:
    print("不存在")
#请输入查找名字:鱼干
#存在

#index()索引查找
list1 = ['a','b','c','a','b']
print(list1.index('a',1,4))#从1-4下标寻找是否存在a
#3
print(list1.count('b'))  #2
2.2.2 列表排序、反转、长度获取

方法名

含义

列表名.sort()

对列表进行永久性排序(升序)

列表名.sort(reverse = True)

降序

sorted(列表名)

函数对列表进行临时排序

列表名.reverse()

对列表元素反转操作

len(列表名)

获取列表长度

liebiao = ['b','a','c']
#字母顺序
liebiao.sort() 
print(liebiao)  #['a', 'b', 'c']

#字母相反顺序
liebiao.sort(reverse = True)
print(liebiao)#['c', 'b', 'a']

#使用函数进行临时排序
liebiao = ['b','a','c']
print(sorted(liebiao))  #['a', 'b', 'c']
print(liebiao)    #['b', 'a', 'c']

#反转
liebiao = ['b','a','c']
liebiao.reverse()
print(liebiao)  #['c', 'a', 'b']
#获取长度
print(len(liebiao))#3

2.3 列表嵌套(遍历、创建)

2.3.1 遍历列表
name = [[],[],[]]  #有3个元素的空列表,每个元素都是一个空列表
name = [['小红','小兰'],['鱼干']]
print(name[0])      #['小红', '小兰']
print(name[0][0])   #小红

for循环

liebiao = ['b','a','c']
for lie in liebiao:
    print(lie)
2.3.2 创建数值列表

函数名

含义

range(1,5)

创建 1,2,3,4

list(range(1,5))

将range结果转为列表

range(1,5,步长)

指定步长

for shuzi in range(1,5):
    print(shuzi)
    
liebiao = list(range(1,6))
print(liebiao)

#指定步长
liebiao1 = list(range(1,6,2))
print(liebiao1)


#创建列表包含前10个数的平方
squares = []
for value in range(1,11):
    squares.append(value ** 2)
print(squares)
2.3.2 最大值、最小值、总和
digits = [1,2,3,4,5]
print(min(digits))
print(max(digits))
print(sum(digits))
2.3.3 列表解析
squares = [value**2 for value in range(1,11)]
print(squares)

2.4 使用列表的一部分

2.4.1 切片
digits = [1,2,3,4,5]
print(digits[0:3])  #
print(digits[:3]) #从头开始
print(digits[1:]) #终止至末尾 
print(digits[-3:])#最后三个元素
2.4.2 遍历切片
digits = [1,2,3,4,5]
for digit in digits[:3]:
    print(digit)
2.4.3 复制列表
digits = [1,2,3,4,5]
fuzhi = digits[:]
print(fuzhi)

2.5 练习

8个老师随机放入三个办公室中
#8个老师随机放到3个办公室

import random   #随机数生成

offices = [[],[],[]]   #三个办公室
names = ['A','B','C','D','E','F','G','H']   #8个老师
for name in names:
    index = random.randint(0,2)   #老师随机分配三个列表,索引为0,1,2
    offices[index].append(name)   #将老师名字加入列表中
i = 1
for office in offices:
    print("办公室%d的人数为:%d"%(i,len(office)))   #输出办公室(1开始),所容纳人数
    i += 1
    for name in office:
        print("%s"%name,end='\t')
    print('\n')
    print("-"*10)
购物车

根据products列表写一个循环,不断询问用户买什么,用户选择一个商品编号后,就把对应商品添加到购物车中,最终输入q退出,打印购买商品列表

products = [['ipone',6888],['MacPro',14800],['小米6',2499],['coffee',31],['Book',60],['Nike',699]]
#第一问
print('-'*4 + '商品列表' + '-'*4)
index = 0
for shop in products:
    print("%d\t%s\t%d"%(index,shop[0],shop[1]))
    index += 1
print("================")
for i in range(6):
    print("%d\t%s\t%d" % (i, products[i][0], products[i][1]))
    i +=1
#第二问  
list = []  #购物车列表
money = 0
i = 0
while i < len(products):
    num = input("请输入您想购买商品的编号")
    if num == 'q':
        break
    num = int(num)
    list.append(products[num])
for shop in list:
    money += shop[1]
print("购物车里有:",list,"共花费%d"%money)

第3章 元组

3.1 元组介绍

  • 采用()标识,似列表,但不可修改
  • 无append(),insert(),用"+"连接
  • 有序集合,与列表相同索引方法 calssmates = (‘1’,’2’,’3’)
    classmates[0] classmates[0:2],classmates[:2],classmates[1:]
  • 列表和元组都是有序集合,但是列表可以修改,元组不可以。
    禁止修改元组
#元组的定义与输出
yuanzu = (200,50)
print(yuanzu[0])     #200
#元组只含一个元素时,需要用,,否则不任务是元组类型
a = (1)
print(type(a))  #<class 'int'>
a = (1,)
print(type(a)) #<class 'tuple'>

第4章 if语句

cars = ['audi','bmw','subaru']
for car in cars:
    if car == 'bmw':
        print(car.upper())
    else:
        print(car.lower())

4.1 条件测试

符号

含义

==

检查是否相等

!=

检查是否不相等

and /or

检查多个条件

in

检查特定值是否包含在列表中

not in

检查特定值是否不包含在在列表中

car = 'ab'
print(car == 'ab') #True

print(car == 'AB')#False

print(car != 'AB')#True

print('ab' in car)#True

4.2 if-elif-else语句

4.4 多个elif语句

4.5 省略else代码块

第5章 字典

字典是一系列键对值

5.1 使用字典

  • 字典名.get()
zidian= {'yanse':'red','num':12}
print(zidian['yanse'])   #red
print(zidian.get("yanse")) #red

print(zidian.get("age","m")) #没有找到会返回默认值m

new_zidian = zidian['num']
print("my old is" +' ' + str(new_zidian))#my old is 12

5.2 增、删、改

  • pop(key)
  • del.clear()删除所有元素
zidian= {'yanse':'red','num':12}
#添加键值对
zidian['name'] = '鱼干'
print(zidian)   
#{'yanse': 'red', 'num': 12, 'name': '鱼干'}

#修改字典中的值
zidian['yanse' ] = 'blue'
print(zidian)
#{'yanse': 'blue', 'num': 12, 'name': '鱼干'}

#删除键值对,再次访问会报错
del zidian['name']
print(zidian)
#{'yanse': 'blue', 'num': 12}

#清空
zidian.clear()
print(zidian)
#{}

5.3 遍历(查)字典

方法名

含义

字典名.items()

返回一个键-值对列表,每对

字典名.keys()

返回键,不使用值,列表形式

字典名.values()

遍历字典中所有值

sorted(字典名.keys())

特定顺序返回元素

set(字典名.values())

集合,使所有的值输出时没有重复项

#遍历字典中的所有键值对
zidian= {'yanse':'red','num':"12",'a':'red'}
for key,value in zidian.items():
    print("\nkey:" + key)
    print("value:"+value)
    
#遍历字典中的所有键
for k in zidian.keys():
    print("\nkey:" + k)
    
#按顺序遍历字典中的所有键
for k in sorted(zidian.keys()):
    print("\nk:" + k)
    
#遍历字典中的所有值
for v in zidian.values():
    print("\nvalues:" + v)

for v in set(zidian.values()):
    print("\nvalues:" + v.title())

5.4 嵌套

5.4.1 字典列表
alien_0 = {'color':'red','points':5}
alien_1 = {'color':'yellow','points':10}
alien_2 = {'color':'red','points':15}

aliens = [alien_0,alien_1,alien_2]
for alien in aliens:
    print(alien)
#{'color': 'red', 'points': 5}
#{'color': 'yellow', 'points': 10}
#{'color': 'red', 'points': 15}

#自主创建30个外星人
aliens = []
for alien_number in range(30):
    new_alien = {'color':'red','points':5,'speed':'slow'}
    aliens.append(new_alien)
#显示前5个外星人
for alien in aliens[:5]:
    print(alien)
print("...")
#显示创建了多少个外星人
print("Total number of aliens:"+ str(len(aliens)))
#修改前三个外星人
for alien in aliens[0:3]:
    if alien['color'] == 'red':
        alien['color'] = 'yellow'
        alien['speed'] = 'medium'
        alien['points'] = 10
for alien in aliens[:5]:
    print(alien)
5.4.2 字典中存储列表

每当需要在字典中将一个键关联到多个值时,都可以在字典中嵌套一个列表

pizza = {'crust':'thick',
         'toppings':['mushrooms','extra cheese'],
         }
print("你点了一个" + pizza['crust' ]+ " pizza"+ "有下面的属性" )
for topping in pizza['toppings']:
    print("\t" + topping)
    
    
like_yuyan = {'liu':['python','c'],
              'xu':['c'],
              'wang':['c','R']}

for name,languages in like_yuyan.items():
    if len(languages) == 1:
        for lan in languages:
            print("\n" + name.title()+"'s like languages is:" + lan.title())
    else:
        print("\n" + name.title()+"'s like languages are:")
        for language in languages:
            print("\t" + language.title())
5.4.3 在字典中存储字典
#在字典中存储字典
users = {
    'a':{'first':'alert',
         'last':'el',
         'location':'pri',},
    'b':{'first':'as',
         'last':'de',
         'location':'bcsdbh',},
    }

for username,user_info in users.items():
    print("\nUsername:" + username)
    full_name = user_info['first']+" "+user_info['last']
    location = user_info['location']
    print("\tFull name:" + full_name.title())
    print("\tlocation:" + location.title())
5.4.4 字典枚举

enumerate()枚举函数

  • 使用枚举函数,同时获得列表中的下标和元素内容
mylist = ['a','b','c','d']
print(enumerate(mylist))
#<enumerate object at 0x0000024642389A80>

for i,x in enumerate(mylist):
	print(i,x)
#0 a
#1 b
#2 c
#3 d

字典、列表、元组、集合

名称

是否有序

特点

列表 []

有序

可修改,[]标识,append()替换、insert()插入,pop()删除

元组()

有序

不可修改,()标识

字典{}

无序

key不可变val可变,key-value数据对,{}标识,直接增加修改,pop()删除

集合{}

无序

可变,{}或set()创建,in/not in判断是否存在,add添加、remove删除可用作去重

第6章 用户输入与循环

6.1用户输入intput()

#input输入内容
information = input("输入内容:")
print(information)
#int()
information = int(information)
print(information > 1)#True

6.2 while循环

循环终止

含义

break

提前退出循环

continue

跳出当前循环,直接开始下一次循环

代码有问题时,程序进入“死循环”,用Ctrl+C退出程序或者强制结束进程

#使用while循环
num = 1
while num <= 5:
    print(num)
    num += 1
    
 #让用户选择什么时候退出
prompt = "\nTell me something,and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program."
message = ""
while message != 'quit':   
    message = input(prompt)
    if message != 'quit':
        print(message)

#使用标志
prompt = "\nTell me something,and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program."

flag = True  #标志位
while flag:
    message = input(prompt)
    if message == 'quit':
        active = False
    else:
        print(message)

while与else

#while与else的组合
i= 0
while i < 5:
    print(i,"<5")
    i += 1
else:
    print(i,'>=5')

6.3 while循环处理列表和字典

  • for循环是一种遍历列表的有效方式,但在for循环中不应修改列表
  • 要在遍历列表的同时对其进行修改,可使用while循环
6.3.1 在列表间移动数据
#首先,创建一个待验证用户列表和一个用于存储已验证用户的空列表
unconfirmed_users = ['alice','brian','candace']
confirmed_users = []
#验证每个用户,知道没有未验证用户为止
#将每个经过验证的列表都移到已验证用户列表中
while unconfirmed_users:
    current_user = unconfirmed_users.pop()  #从末尾开始删除
    print('Verifying user:' + current_user.title())
    confirmed_users.append(current_user)
#显示所有已验证的用户
print("\nThe following users have been confirmed:")
for confirmed_user in confirmed_users:  
    print(confirmed_user.title())
6.3.2 删除包含特定值的所有列表元素
pets = ['dog','cat','dog']
print(pets)

while 'dog' in pets:
    pets.remove('dog')
print(pets)
6.3.3 使用用户输入来填充字典
responses = {}
active = True #标志位
while active:
    name = input("请输入名字")
    response = input("喜欢哪座山")
    responses[name] = response
    repeat = input("是否继续(yes/no)")
    if repeat == 'no':
        active = False
for name,response in responses.items():
    print(name + "would like to climb " + response + ".a")

6.4 for…in…

#循环范围
for i in range(5):
    print(i)
    
for i in range(0,10,3): #[0,10),b步长为3
    print(i)

for i in range(1,10,3):
    print(i)
#循环与字符串
name = 'yugan'
for i in name:
    print(i,end = '\t')
#循环与列表
a = ['aa','bb','cc']
for i in a:
    print(i,end = '\t')

a = ['aa','bb','cc']
for i in a:
    print(i,end = '\t')
print('\n')
for i in range(len(a)):
    print(i,a[i])

9*9乘法表

sum = 0
for i in range(1,10):
    for j in range(1,i+1,):
        sum = i*j
        print("%d * %d = %d"%(i,j,sum),end = '\t')
    print(' ')

print('==================')
i = 1
sum = 0
while i < 10:
    j = 1
    while j < i+1:
        sum = i * j
        print("%d * %d = %d" % (i, j, sum), end='\t')
        j += 1
    i += 1
    print(' ')

第7章 函数

7.1 定义函数

def 函数名(参数):         #形参
    函数体
函数名(参数)               #调用,实参
def greet_user():
    print("Hello!")
greet_user()   #Hello!

def greet_user(name):
    print("Hello,"+name.title())
greet_user('鱼干')   #Hello,鱼干

7.2 传递实参

  • 位置实参:
  • 关键字实参:
  • 默认值:先列出无默认值的形参,在列出有默认值的形参,默认值后面必须全是默认值;与默认值不同直接进行赋值即可
#位置实参
def pets(types,name):
    print("\nI have a " + types +","+"my "+types+"'s name is "+ name.title())

pets('cat','li')
#I have a cat,my cat's name is Li    
    
#关键字实参
def pets(types,name):
    print("\nI have a " + types +","+"my "+types+"'s name is "+ name.title())

pets(types ='cat',name ='li')       
#I have a cat,my cat's name is Li

#默认值   先列出无默认值的形参,在列出有默认值的形参
def pets(types,name = 'li'):
    print("\nI have a " + types +","+"my "+types+"'s name is "+ name.title())

pets(types ='cat')  
#I have a cat,my cat's name is Li

7.3 返回值

*调用返回值的函数时,需要提供一个变量,用于存储返回的值

#返回简单值
def pets(types,name):
    full = "I have a " + types +","+"my "+types+"'s name is "+ name.title()
    return full.title()
    
bianlaing = pets('dog','li')
print(bianlaing)
#I Have A Dog,My Dog'S Name Is Li

#返回多个值的函数
def divid(a,b):
    yushu = a % b
    shang = a // b
    return yushu,shang

yu,sh = divid(5,2)
print(yu,sh)
# 1 2

#返回字典
def person(firstname,lastname):
    per = {'first':firstname,'last':lastname}
    return per
    
mu = person('li','ih')
print(mu)
#{'first': 'li', 'last': 'ih'}

#添加可选形参
def person(firstname,lastname,age = ''):
    per = {'first':firstname,'last':lastname}
    if age:
        per['age'] = age
    return per
    
mu = person('li','ih',age = 27)
print(mu)
#{'first': 'li', 'last': 'ih', 'age': 27}

7.4 传递列表

def users(names):
    for name in names:
        msg = "Hello, " + name.title() + "!"
        print(msg)
user = ['ha','li','kj']
users(user)

7.5 传递任意数量的实参

  • 使用 *形参名 创建一个空元组
  • 使用 **形参名 创建一个空字典
def make_pizza(*toppings):
	for topping in toppings:
		print("- "+toppings)
make_pizza('mu','de','des')
##创建一个空字典,
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('al', 'ei', 
                             location = 'pri',
                             field = 'ph')
print(user_profile)

7.6 将函数存储在模块中

import 模块名
	模块名.函数名()
	
#导入特定的函数
from 模块名 import 函数名
	函数名()
	
#函数名较长时可使用as给函数指定别名
from 模块名 import 函数名 as 别名
	别名()
	
#使用as给模块指定别名
import 模块名 as 别名
	别名.函数名()
	
#导入模块中的所有函数
from 模块名 import *

7.7 lambda函数

  • 特殊函数-匿名函数
  • 使用方法:<函数名>=lambda<参数列表>:<表达式>
  • 用于简单的、能够在一行内表示的函数,计算结果为返回值
定义计算函数
"""
def futures_value(gramvalue,metalounceusd,rate):
    output = gramvalue/OUNCE_VS_GRAM * metalounceusd * rate
    return output
"""
futures_value = lambda gramvalue,metalounceusd,rate:gramvalue/OUNCE_VS_GRAM * metalounceusd * rate

第8章 类

  • 使用类来创建对象被称为实例化

8.1 创建和使用类

  • class 类名(): 类名首字母需大写
  • __ init__(self,形参,) 方法
  • self必不可少
  • 以self为前缀的变量都可供类中的所有方法使用
  • __ init__()并未显示地包含return语句
  • 首字母大写的名称指的是类,小写的名称指的是根据类创建的实例
  • 访问属性: 实例名.属性名
  • 调用方法:实例名.方法名()
####创建Dog类
class Dog():
    #一次模拟小狗的简单尝试
    def __init__(self,name,age):
        # 初始化属性name和age
        self.name = name
        self.age = age
    def sit(self):
        #模拟小狗被命令时蹲下
        print(self.name.title() + " is now sitting.")
    def roll_over(self):
        #模拟小狗并命令时打滚
        print(self.name.title() + " rolled over!")

my_dog = Dog('Willlw',6)    #my_dog为实例
print("My dog's name is "+my_dog.name.title() + ".")
print("My dog is " +str(my_dog.age) + "years old.")
    
####访问属性
print(my_dog.name )
####调用方法
my_dog.sit()
my_dog.roll_over()

8.2 使用类和实例

  • 给属性指定默认值
  • 类中每个属性都必须有初始值,即便是0或空字符串
  • 设置默认值时,在方法__init__()内指定初始值可以,指定初始值后,就无须包含它提供的形参
  • 直接修改属性的值
  • 直接修改属性的值
  • 通过实例直接访问 实例名.属性名 = 修改值
  • 通过方法修改属性的值
  • 通过方法对属性的值进行递增
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):
        #将里程表读数
        self.odometer_reading = mileage
        
    ####通过方法对属性的值进行递增
    def increment_odometer(self,miles):
        #将里程表读数增加指定的量
        self.odometer_reading += miles
    
my_new_car = Car('audi','a4',2016)
print(my_new_car.get_descriptive_name())

my_new_car.read_odometer()   #属性指定默认值

####直接修改属性的值
my_new_car.odometer_reading = 23
my_new_car.read_odometer()   #属性指定默认值

####通过方法修改属性的值
my_new_car.update_odometer(24)
my_new_car.read_odometer()   #属性指定默认值

####通过方法对属性的值进行递增
my_used_car = Car('subaru','outback',2013)
print(my_used_car.get_descriptive_name())

my_used_car.update_odometer(23500)
my_used_car.read_odometer()   

my_used_car.increment_odometer(100)
my_used_car.read_odometer()

8.3 继承

  • 当要编写的类是另一个现成类的特殊版本时,可使用继承;
  • 一个类继承另一个类时,它将自动获得另一个类的所有属性和方法;
  • 原有的类成为父类,而新类称为子类;子类继承了其父类的所有属性和方法,同时还可以定义自己的属性和方法
  • 定义子类时,必须在括号内指定父类的名称,且父类需要在子类前面
8.3.1 子类的方法__init__()
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
####子类ElectricCar
class ElectricCar(Car):
    #电动汽车的独特之处
    def __init__(self,make,model,year):
        #初始化父类的属性
        #super()帮助python将父类和子类关联起来,调用父类的__init__方法,
        super().__init__(make,model,year)

my_tesla = ElectricCar('tesla', 'model s',2016)
print(my_tesla.get_descriptive_name())
8.3.2给子类定义属性和方法
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
####子类ElectricCar
class ElectricCar(Car):
    #电动汽车的独特之处
    def __init__(self,make,model,year):
        #初始化父类的属性
        #super()帮助python将父类和子类关联起来,调用父类的__init__方法,
        #初始化父类的属性,在初始化电动汽车特有的属性
        super().__init__(make,model,year)
        self.battery_size = 70 #新的属性,子类有父类无
    
    def describe_battery(self):
        #打印一条描述电瓶容量的消息
        print("This car has a "+str(self.battery_size)+"-kWh battery.")

my_tesla = ElectricCar('tesla', 'model s',2016)
print(my_tesla.get_descriptive_name())
my_tesla.describe_battery()
8.3.3重写父类的方法
  • 子类中与要重写的父类方法同名
8.3.4将实例用作属性
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 Battery():
      def __init__(self,battery_size = 70):
          #初始化电瓶的属性
          self.battery_size = battery_size
      def describe_battery(self):
          print("Thiscar has a "+str(self.battery_size)+"-kWh battery.")
        
        
        
        
####子类ElectricCar
class ElectricCar(Car):
    #电动汽车的独特之处
    def __init__(self,make,model,year):
        #初始化父类的属性
        #super()帮助python将父类和子类关联起来,调用父类的__init__方法,
        #初始化父类的属性,在初始化电动汽车特有的属性
        super().__init__(make,model,year)
        self.battery = Battery()
    
    

my_tesla = ElectricCar('tesla', 'model s',2016)

print(my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery()

8.4 导入类

  • 导入单个类
  • 在一个模块中存储多个类
  • 从一个模块中导入多个类
  • from 别名 import 类名,类名
  • 导入整个模块
  • 导入模块中的所有类
  • from 别名 import*
  • 在一个模块中导入另一个模块

第9章 文件和异常

9.1 从文件中读取数据

9.1.1 打开与关闭整个文件
法一
f = open('文件名','w')   #文件不存在时,执行‘w’会新建一个
法二
with  open('文件名')  as   名字:
	变量名 = 名字.read()
	print(变量名)
	
	#关闭文件
	f.close()
#法一
f = open("test.txt",'w')#文件不存在时,执行’w'会写入,新建文件
f.write("hello world")  #将字符串写入文件中
f.close()
  #读取
f = open("test.txt",'r')
content = f.read(3) #读取3个字符  并不是每都是从开头读取,而是顺次读取
print(content)
f.close()
#hel

#法二
#pi_digits.txt文件:
'''	3.1415926535
	  8979323846
	  2643383279
'''
####读取整个文件
with open('pi_digits.txt') as file_object:
    contents = file_object.read()
    #print(contents)#会出现许多空行
    print(contents.rstrip())#删除末尾空白
9.1.2 文件读取
  • read方法,读取指定的字符,开始时定位在文件头部,每执行一次向后移动指定字符数
  • f.readlines() 读取全部内容,以列表形式展示
  • f.readline() 读取一行内容
#法一
#readlines()
f = open("test.txt",'r')
content = f.readlines()
print(content)

i = 1
for temp in content:
    print("%d:%s"%(i,temp))
    i += 1
f.close()
#1:hello world
#2:hello world
#3:hello world
#4:hello world

#法二
#逐行读取
filename = 'pi_digits.txt'

with open(filename) as file_object:
    for line in file_object:
        print(line.rstrip())
#readlines()
filename = 'pi_digits.txt'

with open(filename) as file_object:
    lines = file_object.readlines()
    
for line in lines:
    print(line.rstrip())
9.1.3 使用文件的内容
filename = 'pi_digits.txt'

with open(filename) as file_object:
    lines = file_object.readlines()
    
pi_string = ''   #创建变量用于存储圆周率的值

for line in lines:
    pi_string += line.strip()
    
print(pi_string)   
print(len(pi_string))

9.2 写入文件

名称

含义

‘w’

写入模式。文件已存在则将其覆盖,反之,创建

‘r’

读取模式

‘a’

附加模式,新的内容被写入已有内容之后

‘r+’

打开一个文件用于读写

‘rb’

以二进制格式打开一个文件用于只读。文件指针将会放文件的开头。默认模式

#写入空文件
filename = 'programming.txt'
with open(filename,'w') as file_object:
    file_object.write("I love swimming")
#附加模式打开文件进行写入,不会覆盖原来的内容
filename = 'programming.txt'
with open(filename,'a') as file_object:
    file_object.write("\nI love running")

9.3 文件的相关操作

操作

说明

代码

文件重命名

os模块,rename(需要修改的文件名,新的文件名)

import os os.rename('1.txt','1.txt')

删除文件

remove(待删除的文件名)

import os os.remove('1.txt')

创建文件夹

mkdir(文件夹名)

import os os.mkdir('鱼干')

获取当前目录

getcwd()

import os os.getcwd()

改变默认目录

chdir()

import os os.chdir('../')

获取目录列表

listdir(‘./’)

import os os.listdir('./')

删除文件夹

rmdir()

import os os.rmdir('鱼干')

9.4 异常

举例

try:
    print(num)
except NameError:#异常类型想要被捕获,需要一致
    print("产生错误了")
#产生错误了

#获取错误描述
try:
    print(num)
except NameError as result:#异常类型想要被捕获,需要一致
    print("产生错误了")
    print(result)
  #name 'num' is not defined
#捕获所有异常Exception
try:
    print(num)
except Exception as result:#异常类型想要被捕获,需要一致
    print("产生错误了")
    print(result)
  • 引入异常处理机制可以用来解决程序运行时的错误。当python遇到try语句,先尝试执行try包含的代码块
  • 如果没有错误发生,执行try-except后面的语句
  • 如果发生错误,python寻找一个符合该错误的异常语句,然后执行相应的except的处理代码
  • finally为不管except都进行执行
  • 捕获所有异常:Exception即不用知道具体什么错误

语法(try…finally和嵌套)

try:<body>
except<ErrorType1>:
	<handler1>
except<ErrorType2>:
	<handler2>
except:
	<handler0>
finally:
	<Execute>
  • 文件与异常结合
import time

try:
    f = open('test.txt','r')
    
    try:
        while True:
            content = f.readline()
            if len(content) == 0:
                break
            time.sleep(2)
            print(content)
    finally:
        f.close()
        print("文件关闭")
except Exception as result:
    print("发生异常...")
  • 处理ZeroDivisionError异常
  • try-except代码块处理
  • else代码块
  • 处理FileNotFoundError异常
  • split() 根据字符串创建列表
try:
    print(5/0)
except ZeroDivisionError:
    print("You can't divide by zero!") 

title = "Alice in Wonder"
print(title.split())

9.5 存储数据

名称

含义

json.dump()

存储数据

json.load()

将数据读取到内存

import json #导入json模块
#### json.dump()
numbers = [2,3,5,7,11,13]
filename= 'number.json'
with open(filename,'w') as f_obj:
    json.dump(numbers,f_obj)    
####json.load()
with open(filename) as f_obj:
    numbers = json.load(f_obj)
print(numbers)
9.5.1 重构
  • greet_user()

第10章 测试代码

  • unittest模块提供了代码测试工具

10.1 测试类

  • 断言:检查满足的条件是否满足

方法

用途

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中

  • 方法setUp()