文章目录
- 零、基本数据类型(数据类型)
-
- 1、整数类型
- 2、浮点数
- 3、复数
- 4、字符串
- 5、字节串
- 6、组合类型
- 一、python运行代码片段
- 二、在Windows系统中从终端运行Python程序
- 三、变量
-
- 3.1 变量名
- 四、 错误反馈Traceback
- 五、字符串
-
- 5.1 字符串大小写
- 5.2 合并字符串
- 5.3 制表符\t
- 5.4 换行符\n
- 5.5 字符串删除空白rstrip()、lstrip()
- 5.6 四则运算
- 5.7 str()函数:int型转string 整型转字符型
- 5.8 注释
- 六、列表 可变类型 有序
-
- 6.1 添加元素、删除元素的几种方式
- 6.2 元素排序list.sort、sorted(list)
- 6.3 反转元素排列顺序list.reverse()
- 6.4 确认元素长度len(list)
- 6.5 for循环
- 6.6 range()函数
- 6.7 最大值和最小值,求和
- 6.8 列表解析:一行for循环代码
- 6.9 列表:切片
- 6.10 遍历切片
- 6.11 复制列表:创建一个无索引切片
- 七、tuple元组 不可变类型
- 八、if语句
-
- 8.1 if-else:
- 8.2 if-elif-else:
- 8.3 多个elif:
- 8.4 pass语句
- 九、条件判断:等号=、==;不等于!=;大于等于>=;小于等于<=;多个条件and;或or;
-
- 9.1 in 检查特定值是否包含在列表中
- 十、dict字典 可变类型 无序
-
- 10.0 字典的获取:
- 10.1 添加键值对
- 10.2 删除键值对
- 10.3 修改键值对
- 10.4 遍历字典 :
- 10.5 .keys()方法
- 10.6 .values() 方法
- 10.7 .items()方法 转换后获得元组
- 10.8 zip() 字典生成式
- 10.9 字典列表嵌套
- 10.10 字典列表
- 10.11 字典中储存列表
- 10.12 字典中存储字典
- 十一、set集合 可变类型 无序 不能重复
-
- 11.1 集合创建
- 11.2 集合相关操作
- 11.3 集合间的关系
- 十二、用户输入input()
- 十三、while循环
-
- 13.1 while中使用标志
- 13.2 while 使用break 退出循环
- 13.3 while使用continue
- 13.4 while循环处理列表和字典
- 十四、函数
-
- 14.1 简单函数
- 14.2 函数形参与实参赋值
- 14.3 形参默认值
- 14.4 函数返回值
- 14.5 实参可选
- 14.6 返回字典
- 14.7 结合函数使用while循环
- 14.8 函数传递列表
- 14.9 函数修改列表
- 14.10 禁止函数修改列表
- 14.11 传递任意数量实参
-
- 结合使用位置实参和任意数量实参
- 使用任意数量的关键字实参
- 14.12 函数存储到模块
- 14.13 导入特定函数
- 14.14 as给函数指定别名
- 14.15 as给模块指定别名
- 14.16 导入函数中所有函数
- 十五、类
-
- 1、创建和使用类
- 2、给属性指定默认值
- 3、继承
-
- 给子类定义属性和方法
- 重写父类方法
- 4、导入类
-
- 导入单个类
- 一个模块中存储多个类
- 从一个模块导入多个类
- 导入整个模块
- 导入模块中的所有类
- 5、Python标准库 collections类OrderedDict
零、基本数据类型(数据类型)
| 数值类型( 整数、浮点数、复数 )
| 字节类型( 字符串、字节串 )
| 集合、元组、列表、字典 |
可变数据类型:list(列表)、dict(字典)、set(集合,不常用)
不可变数据类型:数值类型(int、float、bool)、string(字符串)、tuple(元组)
1、整数类型
- 与数学中的整数含义相同,无取值范围;
- 整数包括二进制、八进制、十进制、十六进制等4种表示形式;
二进制:以0b或0B开头:0b1101,-0B10;
八进制:以0o或0O开头:0o456,-0O789;
十进制:123,-321,0;
十六进制:以0x或0X开头:0x1A,-0X2B。
print(1+3)
# 4
- 1
- 2
- 3
- 4
2、浮点数
- 与数学中的实数含义相同,带有小数及小数的数字,存在取值范围;
- 不确定尾数问题:浮点数直接运算,可能产生不确定尾数。可以使用
round()
辅助浮点数运算,消除不确定尾数。
print(0.1+0.2111)
# 0.30000000000000004
print(round(0.1+0.2111,5))
# 0.3111
- 1
- 2
- 3
- 4
- 5
- 6
- 7
3、复数
- z = a+bj,a是实部,b是虚部,a和b都是浮点数;
a = 3 + 2j
print(a)
# (3+2j)
print(type(a))
# <class 'complex'>
print(str(a.real) +":" + str(a.imag))
# 3.0:2.0
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
4、字符串
- 字符串:由0个或多个字符组成的有序字符序列,由一对单引号(’ ‘)或一对双引号(” “)表示
5、字节串
- 字节串是计算机存储空间的表达;
- 由0个或多个字节组成的有序序列,每字节对应值为0-255;
- 字节串由前导符b或B与一对单引号或双引号表示,如:b”a\xf6″;
- 0-255间非可打印字符用\xNN方式表示,N是一个十六进制字符。
- 什么时候使用字节串?
字节串只有在处理跟内存相关的内容或者我们处理的内容和字节的数量密切相关的时候才用字节串。
6、组合类型
列表[]、元组()、字典{}
一、python运行代码片段
>>> print("hello python")
hello python
- 1
- 2
或者
二、在Windows系统中从终端运行Python程序
C:\Users\Administrator\Desktop>python "hello python.py"
hello python
- 1
- 2
三、变量
message = "hello 变量"
print(message)
- 1
- 2
在程序中可随时修改变量的值,而Python将始终记录变量的最新值。
message = "hello 变量"
print(message)
message = "hello 第二个变量"
print(message)
- 1
- 2
- 3
- 4
- 5
3.1 变量名
- 变量名只能包含字母、数字和下划线。变量名可以字母或下划线打头,但不能以数字打头,例如,可将变量命名为msage_1,但不能将其命名为1_mssage。
- 变量名不能包含空格,但可使用下划线来分隔其中的单词。例如,变量名greelmng_message可行,但变量名greeting message会引发错误。
- 不要将Python关键字和函数名用作变量名,即不要使用Python保留用于特殊用途的单词,如print。
- 变量名应既简短又具有描述性。例如,name比n好,stulent_name比s_n好,name_ength比 length_of_persons_name好。慎用小写字母和大写字母O,因为它们可能被人错看成数字1和()。
四、 错误反馈Traceback
message = "hello 第二个变量"
print(mesage)
- 1
- 2
Traceback (most recent call last):
File "main.py", line 5, in <module>
print(mesage)
NameError: name 'mesage' is not defined
- 1
- 2
- 3
- 4
Traceback会指出错误行,并且什么地方出错。
五、字符串
字符串就是一系列字符。在Python中,用引号括起的都是字符串,其中的引号可以是单引号,也可以是双引号。
print("string1'hello',hello2")
print('string2')
- 1
- 2
- 3
5.1 字符串大小写
str1 = "abcd efg"
str2 = str1.title()
print(str2)
- 1
- 2
- 3
str3 = "Abcd Efg"
print(str3 + "==upper:"+str3.upper())
print(str3 + "==lower:"+str3.lower())
- 1
- 2
- 3
5.2 合并字符串
str3 = "Abcd Efg"
print("拼接字符串:"+str3+""+str3)
- 1
- 2
5.3 制表符\t
message1 = "hello python"
message2 = "hello\tpython"
print(message1)
print(message2)
- 1
- 2
- 3
- 4
5.4 换行符\n
message1 = "hello python"
message2 = "hello\tpython"
message3 = "hello\npython"
print(message1)
print(message2)
print(message3)
- 1
- 2
- 3
- 4
- 5
- 6
5.5 字符串删除空白rstrip()、lstrip()
message1 = "python "
message2 = " python "
print(message1.rstrip()+"!")
print("!"+message2.lstrip()+"!")
- 1
- 2
- 3
- 4
message1 = "python "
message2 = " python "
print(message1.rstrip()+"!")
print("!"+message2.lstrip()+"!")
print("!"+message2.lstrip().rstrip()+"!")
print("!"+message2.lstrip(" ").rstrip(" ")+"!")
- 1
- 2
- 3
- 4
- 5
- 6
- 7
5.6 四则运算
a = 5/2
aa = 5//2
b = 5*2
bb = 5**2
c = 5+2.1
d = 5-6
e = (5-8)**2
print(a)
print(aa)
print(b)
print(bb)
print(c)
print(d)
print(e)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
5.7 str()函数:int型转string 整型转字符型
age = 22
message = "hello" + str(age)
print(message)
- 1
- 2
- 3
5.8 注释
使用 # 号
# age = 22
# message = "hello" + str(age)
# print(message)
- 1
- 2
- 3
六、列表 可变类型 有序
list = ['123','python','java_SE']
print(list)
print(list[0])
print(list[2].title())#首字母大写显示
print(list[-1])#访问最后一个元素
- 1
- 2
- 3
- 4
- 5
- 6
- 7
-2返回倒数第二个元素,-3返回倒数第三个元素,以此类推。
6.1 添加元素、删除元素的几种方式
list = ["java",'mysql','pgsql']
# 末尾添加元素
list.append("python")
# 列中添加元素
list.insert(1,"C++")
# 列中删除元素
del list[1]
print(list)
# 使用pop弹出末尾元素
last = list.pop()
print(last)
print(list)
#使用pop弹出指定位置元素
list.pop(0)
print(list)
#根据值删除元素
list.remove('mysql')
print(list)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
6.2 元素排序list.sort、sorted(list)
words = ["exe","zzz","aAa","ppp"]
# 对列表永排序
words.sort()
print(words) #['aAa', 'exe', 'ppp', 'zzz']
#反序排列
words.sort(reverse=True)
print(words) #['zzz', 'ppp', 'exe', 'aAa']
words_1 = ["exe","zzz","aAa","ppp"]
# 临时排序
print(sorted(words_1)) #['aAa', 'exe', 'ppp', 'zzz']
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
6.3 反转元素排列顺序list.reverse()
words = ["exe","zzz","aAa","ppp"]
# 永久反转顺序
words.reverse()
print(words) #['ppp', 'aAa', 'zzz', 'exe']
- 1
- 2
- 3
- 4
6.4 确认元素长度len(list)
words = ["exe","zzz","aAa","ppp"]
print(len(words)) # 4
- 1
- 2
6.5 for循环
people = ["小黑","小红","小蓝"]
for i in people:
print(i)
# 小黑
# 小红
# 小蓝
- 1
- 2
- 3
- 4
- 5
- 6
6.6 range()函数
for value in range(1,5):
print(value)
# 1
# 2
# 3
# 4
- 1
- 2
- 3
- 4
- 5
- 6
- 7
6.7 最大值和最小值,求和
list = []
for i in range(0,10):
list.append(i)
print(list) #[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(max(list)) #9
print(min(list)) #0
print(sum(list)) #45
- 1
- 2
- 3
- 4
- 5
- 6
- 7
6.8 列表解析:一行for循环代码
squares = [value**2 for value in range(1,10)]
print(squares) #[1, 4, 9, 16, 25, 36, 49, 64, 81]
- 1
- 2
6.9 列表:切片
切片:处理列表部分元素。指定要使用的第一个元素和最后一个元素的索引。和range()一样,到达指定索引前一个元素停止。
players = ["james","kevin","irving","love"]
# 取 索引0 到 索引2 的所有元素
print(players[0:3]) # ['james', 'kevin', 'irving']
# 取列表2~4个的元素 ; 索引1 到 索引3 的所有元素
print(players[1:4]) #['kevin', 'irving', 'love']
- 1
- 2
- 3
- 4
- 5
- 6
- 7
不指定开始索引,则从列表开头取;反之同理:
# 不指定索引
print(players[:4])
#['james', 'kevin', 'irving', 'love']
print(players[1:])
#['kevin', 'irving', 'love']
- 1
- 2
- 3
- 4
- 5
- 6
输出列表最后三个元素:
print(players[-3:])
#['kevin', 'irving', 'love']
- 1
- 2
6.10 遍历切片
for player in players[:3]:
print(player.title())
# James
# Kevin
# Irving
- 1
- 2
- 3
- 4
- 5
6.11 复制列表:创建一个无索引切片
players = ["james","kevin","irving","love"]
copyPL = players[:]
print(copyPL) #['james', 'kevin', 'irving', 'love']
players.append("old")
copyPL.append("new")
#证明两者不是
print(players) #['james', 'kevin', 'irving', 'love', 'old']
print(copyPL) #['james', 'kevin', 'irving', 'love', 'new']
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
七、tuple元组 不可变类型
# 元组
# 使用()
dimension = (200, 50)
print(dimension)
print(type(dimension))
# (200, 50)
# <class 'tuple'>
# 不加括号
dimension_1 = 200, 50
print(dimension_1)
print(type(dimension_1))
# (200, 50)
# <class 'tuple'>
# 使用tuple
dimension_2 = tuple((200, 50))
print(dimension_2)
print(type(dimension_2))
# (200, 50)
# <class 'tuple'>
# 单个需要加逗号 不然就是对应类型
dimension_3 = ('sss')
print(dimension_3)
print(type(dimension_3))
# sss
# <class 'str'>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
# 元组
dimension = (200,50)
for i in dimension:
print(i)
- 1
- 2
- 3
- 4
相比列表,元组是更简单的数据结构。如果要存储一组值在整个生命周期里不变,可使用元组。
list 是可变的对象,元组 tuple 是不可变的对象。
八、if语句
# if
cars = ['audi','bmw','subaru']
for car in cars:
if car == 'bmw':
print(car.upper())
else:
print(car.lower())
# audi
# BMW
# subaru
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
8.1 if-else:
age = 17
if age>=18 :
print(age)
else:
print("too young")
#too young
- 1
- 2
- 3
- 4
- 5
- 6
8.2 if-elif-else:
age = 17
if age<18:
print("too young")
elif age == 18:
print("just enough")
else:
print("right")
# too young
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
8.3 多个elif:
age = 12
if age < 10:
price = 1
elif age > 10 and age < 15:
price = 2
elif age > 15:
price = 3
else:
price = 4
print(price) #2
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
8.4 pass语句
a = 10
if a == 10:
pass
else:
pass
- 1
- 2
- 3
- 4
- 5
九、条件判断:等号=、==;不等于!=;大于等于>=;小于等于<=;多个条件and;或or;
一个等号是陈述,两个等号是发问返回True和False。
判断时会判定大小写不同。若大小写无影响,可转换大小写进行比较。
car = 'bmw';
print(car == 'bmw') #True
print(car == 'BMW') #False
- 1
- 2
- 3
判断两个值不同:!=
and将两个条件测试合二为一,每个表达式都通过,则为True;
or只要有一个语句满足条件,则为True。所有条件不满足,表达式为False;
9.1 in 检查特定值是否包含在列表中
example = ('abs','AAA','K','3A')
print('AAA' in example) #True
- 1
- 2
十、dict字典 可变类型 无序
10.0 字典的获取:
aliens = {'color': 'red', 'points': '5'}
#[]方法
print(aliens['color']) #red
print(aliens['points']) #5
# get方法
print(aliens.get('color'))
# red
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
10.1 添加键值对
aliens = {'color':'red','points':'5'}
aliens['hight'] = 30
aliens['weight'] = 1000
print( aliens )
# {'color': 'red', 'points': '5', 'hight': 30, 'weight': 1000}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
10.2 删除键值对
aliens = {'color':'red','points':'5'}
aliens['hight'] = 30
aliens['weight'] = 1000
print( aliens )
# {'color': 'red', 'points': '5', 'hight': 30, 'weight': 1000}
del aliens['weight']
print( aliens )
# {'color': 'red', 'points': '5', 'hight': 30}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
10.3 修改键值对
aliens = {'color':'red','points':'5'}
aliens['color'] = 'yellow'
print( aliens )
# {'color': 'yellow', 'points': '5'}
- 1
- 2
- 3
- 4
10.4 遍历字典 :
user = {"username":"kevin",
"age":"22",
"gender":"male"}
for key,value in user.items():
print("key:"+key+" value:"+value)
# key:username value:kevin
# key:age value:22
# key:gender value:male
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
10.5 .keys()方法
user = {"username":"kevin",
"age":"22",
"gender":"male"}
# 获取keys
for i in user.keys():
print(i)
# username
# age
# gender
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
aliens = {'color': 'red', 'points': '5'}
for i in aliens:
print(i, aliens[i], aliens.get(i))
# color red red
# points 5 5
- 1
- 2
- 3
- 4
- 5
- 6
- 7
10.6 .values() 方法
user = {"username":"kevin",
"age":"22",
"gender":"male"}
for i in user.values():
print(i)
# kevin
# 22
# male
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
10.7 .items()方法 转换后获得元组
for i in aliens.items():
print(i)
for j in i:
print(j)
# ('color', 'red')
# color
# red
# ('points', '5')
# points
# 5
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
10.8 zip() 字典生成式
keys = ['books', 'tools']
price = [11, 21, 31]
for i in zip(keys, price):
print(i)
# ('books', 11)
# ('tools', 21)
for k, p in zip(keys, price):
print(k, p)
# books 11
# tools 21
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
10.9 字典列表嵌套
alien_o = {'color': 'green ', 'points': 5}
alien_1 = {'color': 'yellow', 'points': 10}
alien_2 = {'color': 'red ', 'points': 15}
aliens = [alien_o, alien_1, alien_2]
for alien in aliens:
print(aliens)
# [{'color': 'green ', 'points': 5}, {'color': 'yellow', 'points': 10}, {'color': 'red ', 'points': 15}]
# [{'color': 'green ', 'points': 5}, {'color': 'yellow', 'points': 10}, {'color': 'red ', 'points': 15}]
# [{'color': 'green ', 'points': 5}, {'color': 'yellow', 'points': 10}, {'color': 'red ', 'points': 15}]
print(type(aliens))
# <class 'list'>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
10.10 字典列表
切片打印前五个
aliens = []
for alien in range(30):
new_alien = {'color':'red ', 'points':15}
aliens.append(new_alien)
for alien in aliens[:5]:
print(alien)
print("...")
# {'color': 'red ', 'points': 15}
# {'color': 'red ', 'points': 15}
# {'color': 'red ', 'points': 15}
# {'color': 'red ', 'points': 15}
# {'color': 'red ', 'points': 15}
# ...
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
10.11 字典中储存列表
example = {
"user":["james","kevin","tom"],
"password":"123456"
}
print(example["user"]) #['james', 'kevin', 'tom']
print(example["password"]) #123456
- 1
- 2
- 3
- 4
- 5
- 6
10.12 字典中存储字典
example = {
"example_1" : {"user":["james","kevin","tom"],"password":"123456"},
"example_2" : ["list1","list2","list3"],
"example_3" : "example_3"
}
print(example)
#{'example_1': {'user': ['james', 'kevin', 'tom'], 'password': '123456'}, 'example_2': ['list1', 'list2', 'list3'], 'example_3': 'example_3'}
print( example["example_1"])
#{'user': ['james', 'kevin', 'tom'], 'password': '123456'}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
十一、set集合 可变类型 无序 不能重复
11.1 集合创建
# 使用{}
s = {1, 23, 4, 345, 1, 2, 2}
print(s, type(s))
# {1, 2, 4, 23, 345} <class 'set'>
# 使用set()
s1 = set(range(5))
print(s1, type(s1))
# {0, 1, 2, 3, 4} <class 'set'>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
language = {"james":"c++",
"kevin":"python",
"bob":"java",
"lily":"python"}
for i in set(sorted(language.values())):
print(i)
# python
# java
# c++
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
11.2 集合相关操作
ss = {123, 123, 1, 4, 124, 2}
print(ss)
# {1, 2, 4, 123, 124}
print(123 in ss)
# True
ss.add("11")
print(ss)
# {1, 2, '11', 4, 123, 124}
ss.update({"22", "222", "2222"})
print(ss)
# {'222', 1, 2, '22', 4, '11', '2222', 123, 124}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
11.3 集合间的关系
# 两个集合是否相等 元素相同就相同
s = {10, 20, 30, 40, 50}
s1 = {40, 30, 20, 10, 50}
print(s == s1)
# True
# 判断子集
s2 = {10, 20}
print(s2.issubset(s))
# True
s3 = {10, 21, 22}
print(s3.issubset(s))
# False
# 判断超集
print(s1.issuperset(s2))
# True
print(s3.issuperset(s2))
# False
# 交集
print(s2.isdisjoint(s1))
# False 有交集为False
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
十二、用户输入input()
name = input()
print(name)
- 1
- 2
Python2.7,应使用函数raw input()来提示用户输入。这个函数与Python3中的input ()一样,也将输入解读为字符串。
sentence = "hello please inuput:"
message = ""
message = input(sentence)
print(message)
# hello please inuput:dwadaw
# dwadaw
- 1
- 2
- 3
- 4
- 5
- 6
- 7
十三、while循环
current_num = 1
while current_num <= 5:
print(str(current_num) + " ", end = "")
current_num+=1
# 1 2 3 4 5
- 1
- 2
- 3
- 4
- 5
- 6
python 3.x版本输出不换行格式如下
print(x, end=“”) end=“” 可使输出不换行。
# 使用while循环,当输入exit才停止
sentence = "Display entered:"
message = input("input message - exit or others :\n")
while message != "exit":
message = input(sentence + message)
print(message)
# input message - exit or others :
# hello
# Display entered:hello
#
# Display entered:abc
# abc
# Display entered:abc
#
# Display entered:exit
# exit
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
13.1 while中使用标志
# while中使用标志 当flag不为True时,停止while循环
sentence = "Display entered:"
message = input("input message - exit or others :\n")
flag = True
while flag:
if message != "exit":
message = input(sentence + message)
print(message)
else:
flag = False
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
13.2 while 使用break 退出循环
# 使用break 退出循环
falg = True
variable1 = 1
while falg:
if variable1 <=5:
print(variable1 , end = "")
variable1 += 1
else:
break
# 12345
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
13.3 while使用continue
# 循环中使用 continue
current_number = 0
while current_number <10:
current_number += 1
if current_number % 2 ==0:
continue #跳过本次,执行后面代码
print(current_number, end="") #13579
- 1
- 2
- 3
- 4
- 5
- 6
- 7
13.4 while循环处理列表和字典
处理列表
#验证账户
while unconfirmed:
current = unconfirmed.pop()
print("verifying : "+current.title())
confirmed.append(current)
print("unconfirmed:")
for i in unconfirmed:
print(i.title())
print("all confirmed:")
for i in confirmed:
print(i.title())
# verifying : Tom
# verifying : Kevin
# verifying : James
# unconfirmed:
# all confirmed:
# Tom
# Kevin
# James
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
#删除包含特定值的所有列表元素
pets = [ "dog","cat","dog","goldfish","cat","rabbit","cat" ]
print(pets)
while "cat" in pets:
pets.remove("cat")
print( pets)
# ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
# ['dog', 'dog', 'goldfish', 'rabbit']
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
处理字典
# 使用用户输入填充字典
rs_responses = {}
flag = True
while flag:
name = input("what's your name?")
response = input("what's your favorite weather?")
# 存进字典
rs_responses[name] = response
repeat = input("would you like to continue? yes/no")
if repeat == "no":
flag = False
print( rs_responses )
# what's your name?james
# what's your favorite weather?daylight
# would you like to continue? yes/noyes
# what's your name?kevin
# what's your favorite weather?rainday
# would you like to continue? yes/nono
# {'james': 'daylight', 'kevin': 'rainday'}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
十四、函数
14.1 简单函数
# 问候语简单函数
def greet_user():
print("hello!")
greet_user() #hello!
- 1
- 2
- 3
- 4
- 5
def greet_user(username):
print("hello!" + username.title() + "!")
greet_user("tom") #hello!Tom!
- 1
- 2
- 3
- 4
14.2 函数形参与实参赋值
def describe_pet(animal_type, pet_name):
print("I have a " + animal_type)
print("My " + animal_type + " name is " + pet_name)
describe_pet("dog", "wangwang")
#I have a dog
# My dog name is wangwang
- 1
- 2
- 3
- 4
- 5
- 6
- 7
def describe_pet(animal_type, pet_name):
print("I have a " + animal_type)
print("My " + animal_type + " name is " + pet_name)
describe_pet(pet_name="wangwang", animal_type="dog")
#I have a dog
#My dog name is wangwang
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
14.3 形参默认值
def describe_pet(pet_name, animal_type="dog"):
# def describe_pet(animal_type="dog",pet_name): 报错
print("My " + animal_type + " name is " + pet_name)
describe_pet(pet_name="wangwang")
# My dog name is wangwang
- 1
- 2
- 3
- 4
- 5
- 6
14.4 函数返回值
使用return语句返回值到调用函数代码行
def get_formatted_name(first_name,last_name):
full_name = first_name+" "+last_name
return full_name.title()
worker = get_formatted_name("tom","kin")
print(worker) #Tom Kin
- 1
- 2
- 3
- 4
- 5
- 6
14.5 实参可选
def get_formatted_name(first_name, last_name, middle_name=""):
if middle_name:
full_name = first_name + " " + middle_name + " " + last_name
else:
full_name = first_name + " " + last_name
return full_name.title()
worker = get_formatted_name("tom", "kin")
print(worker) # Tom Kin
worker2 = get_formatted_name("tom", "kin", "ray")
print(worker2) # Tom Ray Kin
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
14.6 返回字典
函数可以返回任何值,包含字典与数据结构;
# 返回字典
def build_person(first_name, last_name):
person = {'first': first_name, 'last': last_name}
return person
worker = build_person("will", "smith")
print(worker) #{'first': 'will', 'last': 'smith'}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
14.7 结合函数使用while循环
# 结合函数使用while循环
def get_username(first_name, last_name):
full_name = first_name + " " + last_name
return full_name.title()
while True:
print("please input your name: enter q or others to quit; y to continue")
variable = input("input your choice:")
if variable == "y":
first_name = input("please input your first name:")
last_name = input("please input your last name:")
rs = get_username(first_name, last_name)
print(rs.title())
else:
break
# please input your name: enter q or others to quit; y to continue
# input your choice:y
# please input your first name:yh
# please input your last name:l
# Yh L
# please input your name: enter q or others to quit; y to continue
# input your choice:q
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
14.8 函数传递列表
# 传递列表
def get_username(names):
# 向列表每个元素都发出简单问候
for i in names:
msg = "hello " + i.title()
print(msg)
users = ['james', 'tom', 'kevin']
get_username(users)
# hello James
# hello Tom
# hello Kevin
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
14.9 函数修改列表
# 函数修改列表
users = ['tom', 'james', 'kevin']
temp_list = []
# 模拟交换每个用户
def change_user(original_list, rs_list):
while users:
temp_variable = original_list.pop()
print("user :" + temp_variable)
rs_list.append(temp_variable)
def show_users(rs_list):
print(rs_list)
change_user(users, temp_list)
show_users(temp_list)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
14.10 禁止函数修改列表
使用切片,相当于传值给一个临时变量 change_user(users[:], temp_list) ,user[]内容将不会被pop。
# 禁止函数修改列表
users = ['tom', 'james', 'kevin']
temp_list = []
def change_user(original_list, rs_list):
while original_list:
temp_variable = original_list.pop()
print("user :" + temp_variable)
rs_list.append(temp_variable)
def show_users(rs_list):
print(rs_list)
# 使用切片
change_user(users[:], temp_list)
show_users(users)
show_users(temp_list)
# user :kevin
# user :james
# user :tom
# ['tom', 'james', 'kevin']
# ['kevin', 'james', 'tom']
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
14.11 传递任意数量实参
预先不知道函数需要接受多少个实参
def print_users(*user):
print(user)
customer_1 = ["example1"]
customer_2 = ["example1", "example2", "example3"]
print_users(customer_1) # (['example1'],)
print_users(customer_2) # (['example1', 'example2', 'example3'],)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
*user创建一个空元组
结合使用位置实参和任意数量实参
如果要让函数接受不同类型的实参,必须在函数定义中将接纳任意数量实参的形参放在最后。
def make_pizz(size, *type):
for i in type:
print(str(size) + i)
make_pizz(1, 'a')
make_pizz(3, 'a', 'b', 'c')
# 1a
# 3a
# 3b
# 3c
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
使用任意数量的关键字实参
**user_info两个星号让python创建一个user_info的空字典,并将收到的所有键值对都装到这个字典;
# ** 创建字典
def build_profile(firstname, lastname, **user_info):
profile = {}
profile['firstname'] = firstname
profile['lastname'] = lastname
for key, value in user_info.items():
profile[key] = value
return profile
user_profile = build_profile('james', 'kevin', place="China", fild="physics")
print(user_profile)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
14.12 函数存储到模块
创建一个python文件,pizza.py
def make_pizza(size, *toppings):
"""概述要执着的披萨"""
print("\nMaking a " + str(size) + "inch pizza")
for i in toppings:
print("-" + i)
- 1
- 2
- 3
- 4
- 5
同级目录中main.py 导入模块
import pizza
pizza.make_pizza(16, "pepperoni")
pizza.make_pizza(12, "chicken", "green pepper")
# Making a 16inch pizza
# -pepperoni
#
# Making a 12inch pizza
# -chicken
# -green pepper
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
14.13 导入特定函数
from module_name import function_0,function_1,functrion_2
- 1
创建一个python文件,pizza.py
def make_pizza(size, *toppings):
"""概述要执着的披萨"""
print("\nMaking a " + str(size) + "inch pizza")
for i in toppings:
print("-" + i)
def make_pizza_1(size,*topping):
print("另外一个函数")
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
同级目录中main.py 导入模块
from pizza import make_pizza,make_pizza_1
make_pizza(16, "pepperoni")
make_pizza_1(12, "chicken", "green pepper")
# Making a 16inch pizza
# -pepperoni
# 另外一个函数
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
14.14 as给函数指定别名
给make_pizza 指定别名mp()
# as指定函数别名
# 给make_pizza 指定别名mp()
from pizza import make_pizza as mp
mp(16, "pepperoni")
# Making a 16inch pizza
# -pepperoni
- 1
- 2
- 3
- 4
- 5
- 6
- 7
14.15 as给模块指定别名
import module_name as m
- 1
# 使用as 给模块取别名
# import module_name as m
import pizza as p
p.make_pizza(11,"green pepper")
# Making a 16inch pizza
# -pepperoni
- 1
- 2
- 3
- 4
- 5
- 6
- 7
14.16 导入函数中所有函数
使用星号(*)运算符可让Python导入模块中的所有函数:
pizza.py
def make_pizza(size, *toppings):
"""概述要执着的披萨"""
print("\nMaking a " + str(size) + "inch pizza")
for i in toppings:
print("-" + i)
def make_pizza_1(size,*topping):
print("另外一个函数")
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
main.py
from pizza import *
make_pizza(11,"11")
make_pizza_1(22,"22")
# Making a 11inch pizza
# -11
# 另外一个函数
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
十五、类
1、创建和使用类
创建小狗类:
class Dog:
#class Dog(): 这样定义类也可以
def __init__(self, name, age):
self.name = name
self.age = age
def sit(self):
print(self.name.title() + " sit down")
def roll_over(self):
print(self.name.title + " rolled over")
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
1、方法__init__
类中的函数称为方法
方法__init__
是一个特殊的方法,每当你根据dog类创建新实例时,Pyton都会自动运行它。
在这个方法的名称中,开头和末尾各有两个下划线,这是一种约定,旨在避免Pytiomn默认方法与普通方法发生名称冲突。
我们将方法__init__
定义成了包含三个形参: self、 name和age。在这个方法的定义中,形参self必不可少,还必须位于其他形参的前面。为何必须在方法定义中包含形参self呢?因为Pythom调用这个__init__
方法来创建dog实例时,将自动传入实参self。每个与类相关联的方法调用都自动传递实参self,它是一个指向实例本身的引用,让实例能够访问类中的属性和方法。我们创建dog实例时,Python将调用dog类的方法__init__
。我们将通过实参向dog ()传递名字和年龄,self会自动传递,因此我们不需要传递它。每当我们根据Dog类创建实例时,都只需给最后两个形参(name和age 〉提供值。
class Dog():
def __init__(self, name, age):
self.name = name
self.age = age
def sit(self):
print(self.name.title() + " sit down")
def roll_over(self):
print(self.name.title() + " rolled over")
#创建实例
my_dog = Dog("willie", 6)
print("my dog's name is " + my_dog.name.title() + ", age " + str(my_dog.age))
# my dog's name is Willie, age 6
my_dog.sit() # Willie sit down
my_dog.roll_over() # Willie rolled over
your_dog = Dog("james", 2)
your_dog.sit()
your_dog.roll_over()
# James sit down
# James rolled over
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
2、给属性指定默认值
# 指定默认值
class Car():
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
# 添加一个属性 始终为0
self.test = 0
def get_descript_car(self):
longname = self.make + self.model + str(self.year)
return longname
def read_test(self):
print("car mileage is " + str(self.test))
my_new_car = Car("audi", "a4", 2016)
my_new_car.read_test() # car mileage is 0
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
3、修改属性值
# 指定默认值
class Car:
#class Car(): 这样定义类也可以
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
# 添加一个属性 始终为0
self.test = 0
def get_descript_car(self):
longname = self.make + self.model + str(self.year)
return longname
def read_test(self):
print("car mileage is " + str(self.test))
# 方法修改属性值
def update_test(self, mileage):
self.test = mileage
# 方法递增
def increment_test(self, miles):
self.test += miles
my_new_car = Car("audi", "a4", 2016)
my_new_car.read_test() # car mileage is 0
# 1、直接修改属性值
my_new_car.test = 22
my_new_car.read_test() # car mileage is 22
# 2、通过方法修改属性值
my_new_car.update_test(50)
my_new_car.read_test() # car mileage is 50
# 3、通过方法对属性值进行递增 有时候需要将属性值递增特定的量,而不是将其设置为全新的值。
my_new_car.increment_test(99)
my_new_car.read_test() # car mileage is 149
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
3、继承
编写类时,并非总是要从空白开始。如果你要编写的类是另一个现成类的特殊版本,可使用继承。
一个类继承另一个类时,它将自动获得另一个类的所有属性和方法,原有的类称为父类,而新类称为子类。
子类继承了其父类的所有属性和方法,同时还可以定义自己的属性和方法。
# 模拟汽车
class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
self.mileage = 0
def get_car(self):
print(self.make + " " + self.model + " " + str(self.year) + " : " + str(self.mileage) + " mileage")
def read_mileage(self):
print(self.mileage)
def update_mileage(self, mile):
if mile > self.mileage:
self.mileage = mile
else:
print("can't roll back mileage")
def increment_mileage(self, mile):
self.mileage += mile
# 模拟电动汽车
class ElectricCar(Car):
def __init__(self, make, model, year):
super().__init__(make, model, year)
my_tesla = ElectricCar("tesla", "model s", 2016)
my_tesla.get_car() # tesla model s 2016 : 0 mileage
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
给子类定义属性和方法
# 模拟汽车
class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
self.mileage = 0
self.gas = 100
def get_car(self):
print(self.make + " " + self.model + " " + str(self.year) + " : " + str(self.mileage) + " mileage")
def read_mileage(self):
print(self.mileage)
def update_mileage(self, mile):
if mile > self.mileage:
self.mileage = mile
else:
print("can't roll back mileage")
def increment_mileage(self, mile):
self.mileage += mile
def fill_gas_tank(self):
print("car gas tank : " + str(self.gas))
# 模拟电动汽车
class ElectricCar(Car):
def __init__(self, make, model, year):
super().__init__(make, model, year)
# 子类定义属性
self.batter_size = 100
# 定义子类特定的方法
def describe_battery(self):
# 容量
print("capacity : " + str(self.batter_size))
# 重写fill_gas_tank
def fill_gas_tank(self):
print("electricCar dont need gas tank")
# 继承
my_tesla = ElectricCar("tesla", "model s", 2016)
my_tesla.get_car() # tesla model s 2016 : 0 mileage
# 定义子类特定的方法
my_tesla.describe_battery() # capacity : 100
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
重写父类方法
# 模拟汽车
class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
self.mileage = 0
self.gas = 100
def get_car(self):
print(self.make + " " + self.model + " " + str(self.year) + " : " + str(self.mileage) + " mileage")
def read_mileage(self):
print(self.mileage)
def update_mileage(self, mile):
if mile > self.mileage:
self.mileage = mile
else:
print("can't roll back mileage")
def increment_mileage(self, mile):
self.mileage += mile
def fill_gas_tank(self):
print("car gas tank : " + str(self.gas))
# 模拟电动汽车
class ElectricCar(Car):
def __init__(self, make, model, year):
super().__init__(make, model, year)
# 子类定义属性
self.batter_size = 100
# 定义子类特定的方法
def describe_battery(self):
# 容量
print("capacity : " + str(self.batter_size))
# 重写fill_gas_tank
def fill_gas_tank(self):
print("electricCar dont need gas tank")
# 继承
my_tesla = ElectricCar("tesla", "model s", 2016)
my_tesla.get_car() # tesla model s 2016 : 0 mileage
# 定义子类特定的方法
my_tesla.describe_battery() # capacity : 100
# 重写父类方法
my_tesla.fill_gas_tank() # electricCar dont need gas tank
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
4、导入类
导入单个类
from car import Car
- 1
import语句让Python打开模块car.py ,并导入其中的Car类。
一个模块中存储多个类
ElectricCar.py
# 模拟汽车
class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
self.mileage = 0
self.gas = 100
def get_car(self):
print(self.make + " " + self.model + " " + str(self.year) + " : " + str(self.mileage) + " mileage")
def read_mileage(self):
print(self.mileage)
def update_mileage(self, mile):
if mile > self.mileage:
self.mileage = mile
else:
print("can't roll back mileage")
def increment_mileage(self, mile):
self.mileage += mile
def fill_gas_tank(self):
print("car gas tank : " + str(self.gas))
# 模拟电动汽车
class ElectricCar(Car):
def __init__(self, make, model, year):
super().__init__(make, model, year)
# 子类定义属性
self.batter_size = 100
# 定义子类特定的方法
def describe_battery(self):
# 容量
print("capacity : " + str(self.batter_size))
# 重写fill_gas_tank
def fill_gas_tank(self):
print("electricCar dont need gas tank")
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
新建一个名为my_electric_car.py的文件,导入ElectricCar类,并创建一辆电动汽车了:
from ElectricCar import ElectricCar
my_tesla = ElectricCar('tesla', 'model', 2021)
my_tesla.get_car() # tesla model 2021 : 0 mileage
- 1
- 2
- 3
- 4
- 5
从一个模块导入多个类
from ElectricCar import Car, ElectricCar
- 1
导入整个模块
你还可以导入整个模块,再使用句点表示法访问需要的类。这种导入方法很简单,代码也易于阅读。
import car
my_tesla = car.Car("audi", "a4", 2021)
print(my_tesla.get_descript_car()) # audia42021
- 1
- 2
- 3
- 4
导入模块中的所有类
from module_name import *
- 1
5、Python标准库 collections类OrderedDict
from collections import OrderedDict
favorite_language = OrderedDict()
favorite_language['jen'] = 'python'
favorite_language['sarah'] = 'java'
favorite_language['tom'] = 'ruby'
favorite_language['phil'] = 'python'
for name, language in favorite_language.items():
print(name.title() + "'s favorite language is " + language.title() + ".")
# Jen's favorite language is Python.
# Sarah's favorite language is Java.
# Tom's favorite language is Ruby.
# Phil's favorite language is Python.
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
蓝色。通过组合不同的RGB值,可创建1600万种颜色。在颜色值(230, 230, 230)中,红色、蓝色和绿色量相同,它将背景设置为一种浅灰色。