一、变量和字符串
1、Python转义字符
>>> print("D:\three\two\one\now")
D: hree wo\one
ow
#加双斜杠进行转义
>>> print("D:\\three\\two\\one\\now")
D:\three\two\one\now
#加“r”进行转义
>>> print(r"D:\three\two\one\now")
D:\three\two\one\now
#使用斜杠进行换行
>>> print("第一句话\n\
... 第二句话\n\
... 最后一句话\n")
第一句话
第二句话
最后一句话
#使用三引号进行换行
>>> print( """
... 第一句话
... 第二句话
... 第三句话
... """)
第一句话
第二句话
第三句话
2、交换变量x,y的值
>>> x = 3
>>> y = 5
>>> z = x
>>> x = y
>>> y = z
>>> print(x,y)
5 3
>>> x = 5
>>> y = 3
>>> x,y = y,x
>>> print(x,y)
3 5
3、字符串加法和乘法
>>> 520 + 1314
1834
>>> '520' + '1314'
'5201314'
>>> 520 * 1314
683280
>>> '1314' * 5
'13141314131413141314'
二、数字类型
1、Python中浮点数精度低
>>> 0.05+0.12
0.16999999999999998
>>> 0.17 == 0.05 + 0.12
False
2、精确计算浮点数—decimal模块
>>> import decimal
>>> a = decimal.Decimal('0.05')
>>> b = decimal.Decimal('0.12')
>>> print(a+b)
0.17
>>> c = decimal.Decimal('0.17')
>>> c == a + b
True
3、Python支持的运算操作
三、布尔类型
1、bool()函数
返回值为True或者False
2、Python逻辑运算符
and:两者同真则为真,一假则为假。
or:两者一真则为真,两假则为假。
not:真变假,假变真。
四、短路逻辑和运算符优先级
1、短路逻辑
从左往右,当第一个操作数有逻辑运算结果时直接输出;只有当第一个操作数的值无法确定运算结果时,才对第二个操作数进行求值。(谁影响结果,就把谁扔出来 )
>>> 3 and 4
4
#4影响结果,输出4
>>> 3 or 4
3
#3判定为true,输出3
>>> 0 and 4
0
#0判定为false,输出0
>>> 0 or 4
4
#4判定为true,影响结果,输出4
>>> (not 1) or (0 and 1) or (3 and 4) or (5 and 6) or (7 and 8 and 9)
4
#也即false or 0 or 4 or 6 or 9,结果为4
五、分支循环
1、条件表达式
判断一个条件,如果这个条件成立,就执行其包含的某条语句或某个代码块。
>>> if 2*2 == 4:
print("确实")
else:
print("不对")
确实
>>> print("确实" if 2*2 ==4 else print("不对"))
>>> score = 75
>>> if 0 <= score < 60:
... level = 'E'
... elif 60 <= score < 70:
... level = 'D'
... elif 70 <= score < 80:
... level = 'C'
... elif 80 <= score < 90:
... level = 'B'
... elif 90 <= score <= 100:
... level = 'A'
... else:
... level = '请输入0-100的数字'
...
...
>>> level
'C'
2、while循环
当while后面的语句始终成立时,执行包含的语句或代码块,否则跳出循环。
>>> Sunday = "yes"
>>> while Sunday == "yes":
... Sunday = input("今天是周日吗?")
...
...
今天是周日吗?yes
今天是周日吗?yes
今天是周日吗?yes
今天是周日吗?no
>>> i = 1
>>> sum = 0
>>> while i <= 100:
... sum += i
... i += 1
>>> print(sum)
5050
#打印乘法口诀表
i = 1
while i <= 9:
j = 1
while j <= i:
print(j,"*",i,"=",j*i,end=" ")
j += 1
print()
i += 1
1 * 1 = 1
1 * 2 = 2 2 * 2 = 4
1 * 3 = 3 2 * 3 = 6 3 * 3 = 9
1 * 4 = 4 2 * 4 = 8 3 * 4 = 12 4 * 4 = 16
1 * 5 = 5 2 * 5 = 10 3 * 5 = 15 4 * 5 = 20 5 * 5 = 25
1 * 6 = 6 2 * 6 = 12 3 * 6 = 18 4 * 6 = 24 5 * 6 = 30 6 * 6 = 36
1 * 7 = 7 2 * 7 = 14 3 * 7 = 21 4 * 7 = 28 5 * 7 = 35 6 * 7 = 42 7 * 7 = 49
1 * 8 = 8 2 * 8 = 16 3 * 8 = 24 4 * 8 = 32 5 * 8 = 40 6 * 8 = 48 7 * 8 = 56 8 * 8 = 64
1 * 9 = 9 2 * 9 = 18 3 * 9 = 27 4 * 9 = 36 5 * 9 = 45 6 * 9 = 54 7 * 9 = 63 8 * 9 = 72 9 * 9 = 81
break和continue语句:
break跳出当前循环,continue跳出当前迭代并继续执行接下来的操作。
无论是break还是continue语句,它们只能作用于一层循环体。
for i in range(1,10,2):
if i == 1:
continue
print(i) #3,5,7,9
for i in range(1,10,2):
if i == 5:
break
print(i) #1,3
3、for循环
格式: for 变量 in 可迭代对象: 执行语句
range()函数:生成一个数字序列,即为可迭代对象,参数只能是整型。有以下三种参数:
range(stop)
range(start , stop)
range(start , stop , step)
for item in "alternative":
print(item,end=' ')
a l t e r n a t i v e
###
for i in range(10):
print(i,end= ' ')
0 1 2 3 4 5 6 7 8 9
###
for i in range(5,10):
print(i,end= ' ')
5 6 7 8 9
###
for i in range(2,10,2):
print(i,end= ' ')
2 4 6 8
###for循环找10以内的素数
for i in range(2, 10):
for j in range(2, i):
if i % j == 0:
break
else:
print(i,'是一个素数')
2 是一个素数
3 是一个素数
5 是一个素数
7 是一个素数
六、列表
1、列表元素
python中的列表可以存放多种类型的数据,比如整数、浮点数、字符等。
如何访问列表中的元素呢?
可以通过索引访问对应元素,索引从0开始,到列表包含元素个数-1为止。
for循环遍历列表元素,下标索引访问列表单个元素,如list[0]、list[1]
长列表访问列表最后一个元素list[-1]、list[len(list) - 1],索引带符号为反向索引。
>>> list = [1, 2, 3, 4, 5, '上山打老虎','ax','cd']
>>> print(list)
[1, 2, 3, 4, 5, '上山打老虎','ax','cd']
>>> list[0]
1
>>> list[5]
'上山打老虎'
>>>list[-1]
'cd'
2、列表切片
列表切片的用法是 list[start,end,step]。
>>> list = [1, 2, 3, 4, 5, '上山打老虎','ax','cd']
>>> list[0:2]
[1, 2]
>>> list[2:6]
[3, 4, 5, '上山打老虎']
>>> list[::2]
[1, 3, 5, 'ax']
>>> list[5:1:-1]
['上山打老虎', 5, 4, 3]
>>> list[::-1]
['cd', 'ax', '上山打老虎', 5, 4, 3, 2, 1]
3、增、删、查、改
#####增
>>> list = [1, 2, 3, 4, 5, '上山打老虎','ax','cd']
>>> list.append("老虎打不到")
#append(),在列表末尾添加一个指定元素
>>> list
[1, 2, 3, 4, 5, '上山打老虎', 'ax', 'cd', '老虎打不到']
>>> list.extend(["打到小松鼠",5])
#extend(),向列表中最后一个元素后面添加一个可迭代对象
>>> list
[1, 2, 3, 4, 5, '上山打老虎', 'ax', 'cd', '老虎打不到', '打到小松鼠', 5]
>>> list.insert(len(list),'hhhh')
#insert(),向列表指定位置插入一个元素
>>> list
[1, 2, 3, 4, 5, '上山打老虎', 'ax', 'cd', '老虎打不到', '打到小松鼠', 5, 'hhhh']
#####删
>>> list = [1,2,2,3,4,5,6,7,8]
>>> list.remove(2)
#remove(),若列表中存在多个匹配的元素,只会删除第一个。若指定元素不存在,则程序报错
>>> list
[1, 2, 3, 4, 5, 6, 7, 8]
>>> list.pop(5)
6
#pop():参数为下标,打印并删除指定下标的元素
>>> list
[1, 2, 3, 4, 5, 7, 8]
>>> list.clear()
#clear(),清空列表中的元素##
>>> list
[]
#####查
>>> list = [1,2,2,2,3,4,4,5,6,7,8,8,10]
>>> list.count(2)
3
#count(),计算元素出现的次数
>>> list.index(10)
12
#index(),查找元素的索引,可设置起始位置和末位置
>>> list.index(8,5,12)
10
>>> list1 = list.copy()
#浅拷贝
>>> list1
[1, 2, 2, 2, 3, 4, 4, 5, 6, 7, 8, 8, 10]
#####改
>>> list = [1,2,2,2,3,4,4,5,6,7,8,8,10]
>>> list[6] = 200
#赋值更改
>>> list
[1, 2, 2, 2, 3, 4, 200, 5, 6, 7, 8, 8, 10]
>>> list[5:] = [11,22,33,44]
#切片更改
>>> list
[1, 2, 2, 2, 3, 11, 22, 33, 44]
>>> list = [9,6,45,23,75,10,3,6,2]
>>> list.sort()
#排序,顺序默认为从小到大
>>> list
[2, 3, 6, 6, 9, 10, 23, 45, 75]
>>> list = [9,6,45,23,75,10,3,6,2]
>>> list.sort(reverse = True)
#排序,顺序为从大到小
>>> list
[75, 45, 23, 10, 9, 6, 6, 3, 2]
>>> list = [9,6,45,23,75,10,3,6,2]
>>> list.reverse()
#翻转列表
>>> list
[2, 6, 3, 10, 75, 23, 45, 6, 9]
4、列表的加法和乘法
加法是拼接两个列表,乘法是重复列表内所有元素若干次
5、嵌套列表
>>> matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> matrix
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> matrix = [[9, 8, 7],
[6, 5, 4],
[3, 2, 1]]
>>> matrix
[[9, 8, 7], [6, 5, 4], [3, 2, 1]]
>>> A = [0]*3#使用循环创建列表
>>> for i in range(3):
A[i] = [0] * 3
>>> A
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
for i in matrix:
for j in i:
print(j,end = ' ')
9 8 7 6 5 4 3 2 1
>>> for i in matrix:
... for j in i:
... print(j,end = ' ')
... print('\n')
...
...
9 8 7
6 5 4
3 2 1
>>> matrix[1][2]#访问二维列表单个元素
4
6、列表推导式
(1)基本语法:[expression for target in iterable ]
>>> list1 = [x*x for x in range(1,5)]
>>> list1
[1, 4, 9, 16]
>>> list2 = [2*x for x in range(1,20) if x%2 == 0]
#列表推导式加上if语句
>>> list2
[4, 8, 12, 16, 20, 24, 28, 32, 36]
>>> list3 = [x*2 for x in 'love']
>>> list3
['ll', 'oo', 'vv', 'ee']
>>> list4 = [ord(x) for x in 'love']
>>> list4
[108, 111, 118, 101]
>>> list5 = [matrix[i][i] for i in range(3)]
#将矩阵副对角线元素提取出来
>>> list5
[9, 5, 1]
>>> list6 = [matrix[i][2-i] for i in range(3)]
#将矩阵主对角线元素提取出来
>>> list6
[7, 5, 3]
>>>list7 = [i for i in word if i[0] == 'F']
#提取首字母为F的字符串
list7
['Four', 'Five', 'For']
>>>list8 = [[x,y] for x in range(5) if x%4==0 for y in range(7) if y%3==0]
#多个条件
list8
[[0, 0], [0, 3], [0, 6], [4, 0], [4, 3], [4, 6]]
七、元组
由于元组和列表是近亲关系,所以元组和列表在实际使用上是非常相似的。可以通过索引访问元组中的元素,也可进行切片操作,但元组内容不可变,不能修改元组内部元素,列表所能进行的‘增’、‘删’、‘改’均不能在元组中使用,唯有‘查’可以,因此元组只能使用count()和index()方法。
(1)打包和解包
生成一个元组称为元组的打包,将元组内的元素分别赋值给不同的变量称为元组的解包。
>>> turple = (1,2,'a','cd')#元组打包
>>> turple
(1, 2, 'a', 'cd')
>>> turple.index(2)#查找元素
1
>>> turple.count('a')#计数
1
>>> x,y,z,w = turple#元组解包
>>> x
1
>>> w
'cd'
>>> y
2
>>> z
'a'
八、字符串
1、大小写字母换来换去
capitalize():字符串首字母大写,其他小写
>>>a = 'Wang Da Bai'
>>>print(a.capitalize())
Wang da bai
swapcase():翻转字符串所有字母的大小写
>>>a = 'Wang Da Bai'
>>>print(a.swapcase())
wANG dA bAI
title():单词首字母大写,其他小写
>>>a = 'Wang Da Bai'
>>>print(a.title())
Wang Da Bai
upper():全变大写
>>>a = 'Wang Da Bai'
>>>print(a.upper())
WANG DA BAI
lower():全变小写(只用于英文)
>>>a = 'Wang Da Bai'
>>>print(a.lower())
wang da bai
casefold():全变小写(可用于英文以外的其他语言)
>>>a = 'Wang Da Bai'
>>>print(a.casefold())
wang da bai
2、左中右对齐
center(width, fillchar=‘’):居中
rjust(width, fillchar=‘’):右对齐
Ijust(width, fillchar=‘’):左对齐
zfill(width):用0填充字符串左侧,多用于数据报表
width参数用于指定字符串的宽度,若指定的宽度小于或等于原字符串,那么则直接输出源字符串
fillchar参数用于指定填充的字符,默认为空格
3、实现字符串的查找功能
count(sub[, start[, end]]):用于查找sub参数指定的子字符串在字符串中出现的次数
>>>a = 'www.baidu.com'
>>>print(a.count('w'))
3
find(sub[, start[, end]]):用于定位sub参数指定的子字符串在字符串中的索引下标值
>>>a = 'www.baidu.com'
>>>b = a.find('u')
>>>print(b)
8
index(sub[, start[, end]]):同find(),但是find在找不到对应的字符串会返回-1,index则抛出异常
>>>a = 'hello world'.index('w')
>>>print(a)
6
4、替换
expandtabs([tabsize=8]):使用空格替换制表符,参数是指定一个tab等于多少个空格
replace(old, new, count=-1):返回一个将old参数指定的子字符串替换为new参数指定的字符串的新字符串,count为替换的次数,默认为-1,相当于替换全部
九、序列
列表、元组和字符串都统称为序列。
可分为可变序列和不可变序列,列表是可变序列,元组和字符串是不可变序列。
十、字典
Python字典是另一种可变容器模型,可存储任意类型对象。如字符串、数字、元组等其他容器模型
因为字典是无序的所以不支持索引和切片。
1、一般格式:
字典名={元素1,元素2,…}
元素以键值对存在==key(键值):value(实值)
>>>dict = {"nane": "张三", "age": 20, "sex": "男"}
>>>print(dict)
{'nane': '张三', 'age': 20, 'sex': '男'}
注意:
①key不可以重复,否则只会保留第一个;
②value值可以重复;
③key可以是任意的数据类型,但不能出现可变的数据类型,保证key唯一;
④key一般形式为字符串。
2、空字典
格式: 字典名={} 或者 字典名=dict()
3、一些基本操作
①增
格式: 字典名[new key]=new value
>>> dict = {"nane": "张三", "age": 20, "sex": "男"}
>>> dict["score"] = 100
>>> print(dict)
{'nane': '张三', 'age': 20, 'sex': '男', 'score': 100}
②删
格式: del 字典名[key]
>>> dict = {'nane': '张三', 'age': 20, 'sex': '男', 'score': 100}
>>> del dict["sex"]
>>> dict
{'nane': '张三', 'age': 20, 'score': 100}
③查
格式: value=字典名[key]
>>>dict = {"name": "张三", "age": 20, "sex": "男"}
>>>value=dict["sex"]
>>>print(value)
男
④改
格式: 字典名[key]=new value
>>>dict = {"name": "张三", "age": 20, "sex": "男"}
>>>dict["name"]="李四"
>>>print(dict)
{'name': '李四', 'age': 20, 'sex': '男'}
4、字典的其他操作
(1)copy():对字典进行浅拷贝
(2)len():获取字典键值对的数量
(3)in()、notin():判断某个键是否在(不在)字典中
(4)list():将字典转换为列表,返回的是由字典的键构成的列表,等于list(x.keys()),想要得到字典的值组成的列表则需要使用list(x.values())
(5)iter():将字典的键构成一个迭代器
(6)reversed():对字典的键值对进行倒序,但是不能对python3.8之前的版本使用,因为之前的版本中的字典键值对是无序的。
5、字典的遍历
①key
for i in dict.keys():
print(i)
name
age
sex
②value
for i in dict.values():
print(i)
李四
20
男
③item
for i in dict.items():
print(i)
('name', '李四')
('age', 20)
('sex', '男')
④key和value
>>> for key,value in dict.items():
... print(key,value)
...
...
name 李四
age 20
sex 男
⑤元素值和对应的下标索引(enumerate())
for i in enumerate(dict):
print(i)
(0, 'name')
(1, 'age')
(2, 'sex')
十一、集合
Python中的集合类型数据结构是将各不相同的不可变数据对象无序地集中起来的容器,就像是将值抽离,仅存在键的字典。类似于字典中的键,集合中的元素都是不可重复的,并且是属于不可变类型,元素之间没有排列顺序。
1、集合的创建方法
①使用花括号,并在其传入多个元素
>>> set = {123,123}
>>> set
{123}
>>> set = {123,456}
>>> set
②使用集合推导式
>>> set = {i for i in 'abcd'}
>>> set
③使用类型构造器set()
>>> set('love')
{'l', 'e', 'v', 'o'}
2、集合的常用方法
>>> set4={'red','green','blue','yellow'}
>>> set4_copy=set4.copy()#复制
>>> others={'black','white'}
>>> set4_copy
{'red', 'blue', 'yellow', 'green'}
>>> set4.add('orange')
>>> set4
{'red', 'blue', 'green', 'orange', 'yellow'}
>>> set4.update(others)#添加元素
>>> set4
{'red', 'white', 'blue', 'black', 'green', 'orange', 'yellow'}
>>> set4.pop()#删除集合元素
'red'
>>> set4
{'white', 'blue', 'black', 'green', 'orange', 'yellow'}
>>> set4.remove('yellow')
>>> set4
{'white', 'blue', 'black', 'green', 'orange'}
>>> set4_copy.clear()#清除元素
>>> set4_copy
set()