快捷键功能
运行:F5
停止运行:ctrl+c
整体缩进:tab
退格缩进:shift+tab
重复上一条语句:alt+p
变量
变量可以以字母数字和下划线组成,不能以 数字 打头,并且python 3已经支持中文变量。
>>> 你 = 3
>>> print(你) #输出函数是print 没有f
3
>>> x = 3
>>> y = 5
>>> print(x,y)
3 5
>>> x,y = y,x #进行变量值交换时更简单的表示方法,不用再申请一个变量保存
>>> print(x,y)
5 3
字符串
python的字符串表示可以使用单引号’ ’ 双引号" " 三引号""" “”"或者’’’ ‘’’
- 引号需要前后配对 ,各种引号除了在区别字符串内引号作用不同外无区别;
- 当字符串内存在多种引号时,使用转义字符’\’ 进行区别,同时可以用作续写行的标记;
- 原始字符串在字符串前面加上r,表示接下来的字符串反斜杠无意义;
- 三引号表示原始内容;
- 字符串的加法表示字符串拼接,字符串乘法自我复制。
#引号的使用
>>> print("double quotation mark!")#双引号字符串
double quotation mark!
>>> print('single quotation mark!')#单引号字符串
single quotation mark!
>>> print("There're two quotation marks at the same time")#同时两种引号
There're two quotation marks at the same time
>>> print('She said, "OK."')
She said, "OK."
#三引号表示原始内容
>>> print(""" this
is
a
test""")
this
is
a
test
#转义字符的使用
>>> print('He said, "it\'s time to show your power!."')#复杂情况用转义字符
He said, "it's time to show your power!."
>>> print("D:\python\tcl\tcl8")
D:\python cl cl8
>>> print("D:\python\\tcl\\tcl8")
D:\python\tcl\tcl8
>>> print(r"D:\python\tcl\tcl8")
D:\python\tcl\tcl8
#引号可以分割行,表示还没有输入完
>>> print("first \n\
second")
first
second
#字符串的加法和乘法
>>> string = "2021"+"04"+"13"
>>> print(string)
20210413
>>> print(string*2)
2021041320210413
结构与缩进
python表示同一层次的方式不是用括号,而是使用tab表示,或者空格(但必须是4的倍数)
if 1>2: #表示某个层次开始时用冒号表示
print("yes!")
else:
print("no")
同时运算结果为真,Python输出tre,否则为false。
分支结构
普通格式
if condition1:
□□□□statement(s):
elif condition2:
□□□□statement(s)
else:
□□□□statement(s)
简单格式
条件为真执行语句 if condition else 条件为假执行语句
>>> a=4
>>> b=3
>>> small=a if a<b else small=b #赋值符号的优先级比较低,等价于small=(a if a<b else b)
SyntaxError: can't assign to conditional expression
>>> small=a if a<b else b
>>> print(small)
3
循环结构
while 条件:
条件为真则执行语句
import random
counts=3
ans=random.randint(1,10)
while counts>0: #当counts>0的时候执行循环
temp=input("guess number:")
guess=int(temp)
if guess == ans:
print("yes!")
break
else:
if guess>ans:
print("bigger!")
else:
print("smaller!")
counts=counts-1
#使用循环嵌套打印99乘法表
>>> i = 1
>>> while i <= 7:
j = 1
while j <= i:
print(j,"*",i,"=",j*i,end="\t") #end表示结束符,这里采用tab来控制格式
j += 1
print() #默认print()的结束符是\n 此处换行
i += 1
for循环
for 变量 in 可迭代对象:
□ □ □ □ statement(s)
可迭代对象是指元素可以被单独提取出来的对象
#range函数 range(start, stop[, step]) 可理解为左闭右开
>>>range(10) # 从 0 开始到 10
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(1, 11) # 从 1 开始到 11
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> range(0, 30, 5) # 步长为 5
[0, 5, 10, 15, 20, 25]
>>> range(0, 10, 3) # 步长为 3
[0, 3, 6, 9]
>>> range(0, -10, -1) # 负数
[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
>>> range(0)
[]
>>> range(1, 0)
[]
#通过for循环打印10以内的素数
for n in range(2,11): #range左闭右开,所以要写到11
for x in range(2,n):
if n % x == 0:
break
else:
print(n)
2
3
5
7
break
break:跳出最里层循环
#打印20以内质数
>>> i = 2
>>> while i <= 20:
j=2
while i > j:
if i % j == 0:
i = i + 1
break
j=j+1
print(i)
i = i + 1
2
3
5
7
9
11
13
15
17
19
21
continue
continue:结束本次执行,继续循环
#打印10以内奇数
>>> i = 0
>>> while i < 10 :
i += 1
if i % 2 == 0:
continue #为偶数时,继续循环,及跳过打印
print(i)
1
3
5
7
9
else
配合while循环可以检测出退出循环的方式
i = 0
while i < 3:
print("体温正常?")
ans = input()
if ans == "yes":
i += 1
else:
break #当体温不正常,就会跳出循环,但是不打印隔离结束
else:
print("隔离结束") #如果是正常循环结束 不是break跳出就会打印隔离结束
数据类型
数字类型
1、整数
2、浮点数
python和c语言一样都是采用IEEE754的标准来存储浮点数的,存在一定的精度误差
>>> i=0
>>> while i<1:
i=i+0.1
print(i)
0.1
0.2
0.30000000000000004
0.4
0.5
0.6
0.7
0.7999999999999999
0.8999999999999999
0.9999999999999999
1.0999999999999999
精确保存方式 Decimal存储
3、复数
>>> x = 2 + 3j
>>> x.real
2.0
>>> x.imag
3.0
4、数据的运算
# 地板除:向下取整
>>> 3//2
1
>>> -3//2
-2
#同时返回商和余数
>>> divmod(3,2)
(1, 1)
>>> divmod(-3,2)
(-2, 1)
#abs(实数) 返回绝对之后 abs(复数)返回复数的模
>>> abs(-1)
1
>>> x = 3 + 4j
>>> abs(x)
5.0
#pow(a,b) 等价于 a**b pow(a,b,c)等价于a**b%c
>>> pow(2,3)
8
>>> 2**3
8
>>> pow(2,3,5)
3
布尔类型
只有两种类型true和false,0和空为0,非0非空为1,python中任何对象都可以做真值测试,可用作if和while判断语句中。
定义为false的对象:none和false
值为0的类型:0,0.0,0j,Decimal(0),Fraction(0,1)分子为0分母为1
空的序列和集合:(),{},[],range(0),’’,set()
逻辑运算
>>> bool(1)
True
>>> 4>5 and 5>4 #等价于 0 and 1
False
>>> 4>5 or 5>4 #等价于 0 or 1
True
>>> 3 and 4 #and必须判断两边是否都为真,所以最后判断的是4
4
>>> "3" or "4" #or在判断第一个字符串“3”就可以判断这个逻辑运算结果为真,最后判断的是“3”
'3'
>>> 0 or 2 and not 3 #优先级 not and or
False
>>> 1 + 2 < 3 - 4 #优先级 乘除加减再比较
False
列表
序列是Python中最基本的数据结构。序列中的每个元素都分配一个数字 - 它的位置,或索引,第一个索引是0,第二个索引是1,依此类推。
Python有6个序列的内置类型,但最常见的是列表和元组。
列表的形式类似c语言的数组,创建只需要在list =[ , , , ]以逗号分隔开即可
元素 | 1 | 2 | 3 | 4 | 5 | “6” |
---|---|---|---|---|---|---|
下标 | 0 | 1 | 2 | 3 | 4 | 5 |
下标 | -6 | -5 | -4 | -3 | -2 | -1 |
>>> list1 = [1,2,3,4,5,"6"]
>>> print(list1)
[1, 2, 3, 4, 5, '6']
>>> print(list1[0])
1
>>> lengt=len(list1)
>>> print(list1[lengt-1])
6
>>> print(list1[-1])
6
>>>
列表切片
list[ a: b]表示下标[ a, b)
list[ : ]表示所有元素
list[ : b]表示下标[ 0, b)
list[a: ]表示下标[a ,下标最大值]
列表跨度
list[strat :end :步长 ]
>>> list2 = [1,2,3,4,5,6]
>>> list2[::2] #每隔两个取一次
[1, 3, 5]
>>> list2[::-1] #翻转字符串
[6, 5, 4, 3, 2, 1]
>>> list2[::-2] #翻转字符串,每隔两个取一次
[6, 4, 2]
增
▷append()在列表末尾添加一个元素
▷extend()在列表末尾添加一个可迭代对象
▷list[len(list)]使用切片方法,添加至末尾
▷insert(添加至下标,添加元素)添加在任意下标之后
>>> list3 = ["red","blue","yellow"]
>#append()添加至末尾
>>> list3.append("green")
>>> list3
['red', 'blue', 'yellow', 'green']
#extend()添加可迭代对象
>>> list3.extend(["pink","white","black"])
>>> list3
['red', 'blue', 'yellow', 'green', 'pink', 'white', 'black']
#列表分片添加至末尾
>>> list3[len(list3):]=["gray","purple"]
>>> list3
['red', 'blue', 'yellow', 'green', 'pink', 'white', 'black', 'gray', 'purple']
#添加至任意位置
>>> list3.insert(0,"zero")
>>> list3.insert(len(list3),"last")
>>> list3
['zero', 'red', 'blue', 'yellow', 'green', 'pink', 'white', 'black', 'gray', 'purple', 'last']
删
▷remove(待删除元素)删除列表中第一个与待删除元素匹配的元素,若没有则会报错
▷pop(下标)删除下标元素,并返回该元素值
▷clear()清空列表
>>> list4 = [1,9,9,9,0,7,1,0]
>>> list4.remove(0) #删除第一个0元素
>>> list4
[1, 9, 9, 9, 7, 1, 0]
>>> list4.remove(6)
Traceback (most recent call last):
File "<pyshell#38>", line 1, in <module>
list4.remove(6)
ValueError: list.remove(x): x not in list
#使用pop()弹出下标对应的元素
>>> list4.pop(0)
1
>>> list4
[9, 9, 9, 7, 1, 0]
#使用clear()清空列表
>>> list4.clear()
>>> list4
[]
改
改的过程分为两步①将对应部分删除②添加可迭代对象到目标位置
list.sort( key=None, reverse=False)
key:主要是用来进行比较的元素,只有一个参数,具体的函数的参数就是取自可迭代对象中,指定可迭代对象
reverse:排序规则,reverse=True 降序,reverse=False 升序(默认)
>>> list5 = [1,2,3,4,'a',"wow"]
>>> list5[2:4]=['b','v']
>>> list5
[1, 2, 'b', 'v', 'a', 'wow']
>>> list6 = [1,4,6,2,5,8,1]
>>> list6.sort()
>>> list6
[1, 1, 2, 4, 5, 6, 8]
>>> list6.reverse()
>>> list6
[8, 6, 5, 4, 2, 1, 1]
#同时运用两个参数的排序
>>> def takeSecond(elem):
return elem[1]
>>> random=[(2,3),(3,2),(5,5,),(6,4),(7,1)]
>>> random.sort(key=takeSecond,reverse=True)
>>> print('按第二个元素降序排列:',random)
按第二个元素降序排列: [(5, 5), (6, 4), (2, 3), (3, 2), (7, 1)]
查
▷count(x)查找列表中,x的个数
▷index(x)查找列表中首个x的下标
▷copy()拷贝列表
>>> list7 = [ 2,4,5,6,7,4,5,2,]
>>> list7.count(2)
2
>>> list7.index(2)
0
>>> list7[list7.index(2)]=3
>>> list7
[3, 4, 5, 6, 7, 4, 5, 2]
>>> copy_list = list7.copy()
>>> cppy_list2 = list7[:]
>>> copy_list
[3, 4, 5, 6, 7, 4, 5, 2]
>>> cppy_list2
[3, 4, 5, 6, 7, 4, 5, 2]
直接赋值:其实就是对象的引用(别名)。
浅拷贝(copy):拷贝父对象,不会拷贝对象的内部的子对象。
深拷贝(deepcopy): copy 模块的 deepcopy 方法,完全拷贝了父对象及其子对象。
#浅拷贝只是引用,指向同一存储空间
>>> x = [1,2,3]
>>> y=x
>>> x[0]=0
>>> y
[0, 2, 3]
#浅拷贝,只拷贝表层不拷贝深层结构
#当只有一层时,浅拷贝的修改互不干扰
>>> a = [0]*3
>>> b = a.copy()
>>> for i in range(3):
a[i]=[1,2,3]
>>> a,b
([[1, 2, 3], [1, 2, 3], [1, 2, 3]], [0, 0, 0])
#具有多层时,浅拷贝会出错
>>> a = [0] *3
>>> for i in range(3):
a[i]=[0]*3
>>> b=a.copy()
>>> a,b
([[0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 0]])
>>> a[1][0]=1
>>> a[1][1]=2
>>> a,b
([[0, 0, 0], [1, 2, 0], [0, 0, 0]], [[0, 0, 0], [1, 2, 0], [0, 0, 0]])
#深拷贝,复制所有的存储结构
>>> import copy
>>> a=[[0,0,0],[1,1,1],[2,2,2]]
>>> c=copy.deepcopy(a)
>>> a[1][1]= -1
>>> a,c
([[0, 0, 0], [1, -1, 1], [2, 2, 2]], [[0, 0, 0], [1, 1, 1], [2, 2, 2]])
加法 对列表进行拼接
乘法 重复拼接该列表
>>> s = [1,2,3]
>>> t = [4,5,6]
>>> s + t
[1, 2, 3, 4, 5, 6]
>>> s*3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
嵌套列表
#简单建立一个两层列表
>>> matrix = [[1,2,3],[4,5,6],[7,8,9]]
>>> matrix
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
#for循环方式建立两层列表
>>> A = [0] * 3
>>> A
[0, 0, 0]
>>> for i in range(3):
A[i] = [0] * 3
>>> A
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> A[1][1]=1
>>> A
[[0, 0, 0], [0, 1, 0], [0, 0, 0]]
#错误方式建立两层列表
>>> B = [[0]*3]*3
>>> B
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> B[1][1]=1
>>> B
[[0, 1, 0], [0, 1, 0], [0, 1, 0]]
>>> A[0] is A[2]
False
>>> B[0] is B[2]
True
#B的三个列表只是对同一对象的三次引用,所谓牵一发而动全身
列表推导式
#对列表进行遍历,在原数据上修改
>>> a = [1,2,3,4,5,6]
>>> for i in range(6):
a[i]=a[i]*2;
>>> a
[2, 4, 6, 8, 10, 12]
#使用列表推导式,直接建立一个新的列表
>>> a = [1,2,3,4,5,6]
>>> a = [i * 2 for i in a] #表示对于a中的每一个元素,都将其乘以2并存放在a中
>>> a
[2, 4, 6, 8, 10, 12]
#建立多层列表
>>> test = [[1,2,3],[4,5,6],[7,8,9]]
>>> [j for i in test for j in test]
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> matrix = [[1,2,3],
[4,5,6],
[7,8,9]]
#使用推导表达式,创建一个只包含矩阵的第二列
>>> a = [matrix[i][1] for i in range(len(matrix))]
>>> a
[2, 5, 8]
#使用推导表达式,创建一个只包含主对角线的列表
>>> b = [matrix[i][i] for i in range(len(matrix))]
>>> b
[1, 5, 9]
#使用推导表达式,创建一个只包含副对角线的列表
>>> c = [matrix[len(matrix)-1-i][i] for i in range(len(matrix))]
>>> c
[7, 5, 3]
#在推导式中可用if筛选符合条件的结果
>>> words = ["great","fish","nice","five"]
>>> [w for w in words if w[0]=='f'] #选出words中以f开头的字符串
['fish', 'five']
#利用推导表达式,表示笛卡儿积
>>> A = ["a,","an ","one ","the "]
>>> B = ["apple","banana","pear"]
>>> [x + y for x in A for y in B]
['a,apple', 'a,banana', 'a,pear', 'an apple', 'an banana', 'an pear', 'one apple', 'one banana', 'one pear', 'the apple', 'the banana', 'the pear']
元组
元组类似于简化的列表,只能查,不能增删改。
>>> tuple1 = (1,2,3)
>>> tuple1 = (1,2,3,2,3)
>>> tuple1.count(2)
2
>>> tuple1.index(3)
2
>>> tuple2 = (2,3,5)
>>> tuple1+tuple2
(1, 2, 3, 2, 3, 2, 3, 5)
>>> tuple1*3
(1, 2, 3, 2, 3, 1, 2, 3, 2, 3, 1, 2, 3, 2, 3)
模块
random——生成伪随机数
描述
random() 方法返回随机生成的一个实数,它在[0,1)范围内。
语法
import random # random()是不能直接访问的,需要导入 random 模块,然后通过 random 静态对象调用该方法。
random.random()
默认情况下random使用当前系统时间作为种子,由此可实现对伪随机数的付现
import random
print( random.randint(1,10) ) # 产生 1 到 10 的一个整数型随机数
print( random.random() ) # 产生 0 到 1 之间的随机浮点数
print( random.uniform(1.1,5.4) ) # 产生 1.1 到 5.4 之间的随机浮点数,区间可以不是整数
print( random.choice('tomorrow') ) # 从序列中随机选取一个元素
print( random.randrange(1,100,2) ) # 生成从1到100的间隔为2的随机整数
a=[1,3,5,6,7] # 将序列a中的元素顺序打乱
random.shuffle(a)
print(a)
伪随机数的复现
>>> x=random.getstate()#获取种子
>>> random.randint(1,10)
10
>>> random.randint(1,10)
1
>>> random.randint(1,10)
9
>>> random.setstate(x)#重置种子
>>> random.randint(1,10)
10
>>> random.randint(1,10)
1
>>> random.randint(1,10)
9
decimal十进制浮点运算
Decimal()函数
>>> from decimal import * #导入模块
>>> a=Decimal('4.2')
>>> b=Decimal('2.1')
>>> a+b #可以确定精度
Decimal('6.3')
>>> x=Decimal(2)
>>> y=Decimal(1)
>>> x+y
Decimal('3')
>>> 2/1
2.0
>>> x/y
Decimal('2')
注意,Decimal函数传入的浮点数必须加引号(”),表示成字符串形式。传入整数时就不用加。Decimal函数的对象类型是decimal.Decimal,可以通过type()函数查看。
getcontext().prec 设定有效数字
>>> getcontext().prec = 4
>>> Decimal('2.2')/Decimal('1.3')
Decimal('1.692')
设定小数位数
>>> Decimal('1.9907').quantize(Decimal('0.00'))
Decimal('1.99')
转换为字符串格式
>>> str(Decimal('1.9907').quantize(Decimal('0.00')))
'1.99'