数据类型和操作

数据类型和操作

常用内置类型

  1. 整数int

  2. 浮点数 float

  3. 布尔值bool

  4. 类型type

  5. 字符串****str

  6. 列表****list

  7. 元组****tuple 用数组array

  8. 集合****set

  9. 字典****dict(映射,map)

  10. 复数complex

  11. 函数function

  12. 模块module

    eg:

print(type(2))

<class 'int'>

print(type(2<2.2))

<class 'bool'>

print(type(type(2)))

<class 'type'>

常用内置常数

true 真
false 假
none 空

math库中数学常量

pi, π=3.14159 精确到可用精度
e, e=1.718281 精确到可用精度
inf, 浮点正无穷大, 等价于float('inf')

print(math.pi)

​ 3.141592653589793

print(-math.inf)

​ -inf

常用内置运算符

算术 :

+,-,*,@(矩阵乘法),/(浮点除) , //整除
**次方, %模运算取余数

关系:

== 一个=赋值

​ 两个==相等

!= 不等

逻辑: and or not

整除// (舍弃小数位)

print ("5/3=",(5/3))

​ 5/3=1

模运算%

print ("5%3=",(5%3))

​ 5%3=2
**整数无法与字符串想加

运算符优先级

优先顺序

print(2+3*4)

14(不是20)

print(5+4%3)

6(不是0)

print(2**3*4)

32(不是4096)

结合律

print(5-4-3)

​ -2(不是4)

print(4**3**2)

​ 262144(不是4096)(从后向前算:先算32==9,然后49==262144)

浮点数误差

短路求值

x y x and y x or y not x not y
t t t t f f
t f f t f t
f f f f t t
f t f t t f
都为t才是t,只要有一个f就是f t和f只要有一个就是t
print(no() and crash())#成功运行

print(crash() and no())#崩溃

print(yes() and crash())#崩溃
print(yes() or crash())#成功运行

print(crash() or yes())#崩溃

print(no() or crash())#崩溃

type vs isinstance

判断x是不是数字

def isNumber(x):
	return((type(x) == int)or(type(x)==float))
print(isNumber(1),isNumber(1.1),isNumber(1+2j),isNumber("p2s"))

t,t,f,f

import numbers
def isNumber(x) :
	return isinstance(x,numbers.Number)
print(isNumber(1),isNumber(1.1),isNumber(1+2j),isNumber("p2s"))

t,t,t,f

总结

*type() 查看对应类型

*常数类型的值不可修改

*默认浮点除,整除//

*注意运算优先级

*逻辑判断,短路求值

posted @ 2023-11-25 17:24  迪士尼在逃南瓜车  阅读(15)  评论(0)    收藏  举报