加法 1 + 1
减法 2 - 1
乘法 2 * 2
除法 6 / 3
取余 5 % 3
乘方 2 ** 3
向下取整 5 // 3
取整 (拓展)
用到 math 库
math.ceil(2.3) 向上取整
math.floor(3.2) 向下取整
注释:# 或者 Ctrl + /
python小数计算不精确,如 print(1.2 - 1.1) 结果:0.099999…987
解决办法:
import decimal
decimal.Decimal("1.2") - decimal.Decimal("1.1")
结果是0.1
赋值,用变量接收 例如:a = 1
4种,int、float、bool、complex
type关键字查看类型
int转化成float
a = 5 # int
b = float(a) # 转化成float
int转化成bool
a = 5 # int
b = bool(a) # a!=0时,b为True
float转化成int
a = 5.5 # int
b = int(a) # 相当于向下取整
a = 'zly' # 单引号,定义字符串
b = "zly" # 双引号,定义字符串
li = [123,"zly","哈哈哈",True] # 定义列表,列表什么都可以放
tu = (123,"zly","哈哈哈",True) # 定义元祖,元祖什么都可以放
li = li = [123,"zly","哈哈哈", True] # 定义列表
print(li[0],li[1]) # 结果123 "zly"
li[0:2] # 结果[123,"zly"],左闭右开
li[:4] # 结果[123,"zly","哈哈哈",True],从0开始取
li[0:] # 结果[123,"zly","哈哈哈",True],取到最后一个
li[0:4:2] # 结果[123,"哈哈哈"],步长为2,默认为1
li[0:-2] # ['123', 'zly']
li = [1,2,3]
tu = (2,3,4)
a = tuple(li) # a = (1,2,3)
b = list(tu) # b = [2,3,4]代码片
如果是字符串转化成元祖和列表,这个字符串的所有元素会被全部拆开,作为元祖和列表的元素,每个元素依然是字符串类型的
s = "hello world"
li = list(s) # li = ['h','e','l','l','o','w','o','r','l','d']
li = [123,'zly',True]
li[0] = 222 # li = [222,'zly',True]
重新赋值
转换成列表
tu = (1,2,3,4,5) # 注意:*b会拆成列表,而不是元祖
a,*b,c = tu # a = 1,b = [2,3,4],c = 5
li = [1,2,3,4,5]
a,*b,c = li # a = 1,b = [2,3,4],c = 5
s = '1,2,3,4,5'
a,*b,c = s # a = 1 b = [',', '2', ',', '3', ',', '4', ','] c = 5