(2)变量类型、运算和字符串编码

python是弱语言类型,不需要显式的声明变量,不需要提前声明变量的类型,python中没有常量

>>>a = 1
>>>print(a)
1

1 保存在内存中

a 是指针,指针中存的是1在内存中的地址,使用a的时候可以访问到内存中的1

>>>a = 1
>>>print(a)
1
>>>id(1)        #查看内存中的地址
4480297984
>>>id(a)        #a 和 1在内存中的地址相同
4480297984
>>>a is 1       #内存中地址相同,is的结果为True
True

变量类型

>>>a = 1
>>>type(a)
<class 'int'>           #整形
>>>b = 1.0
>>>type(b)
<class 'float'>         #浮点型
>>>e = 1 + 1j
>>>type(e)
<class 'complex'>       #复数
>>>c = "abc"
>>>type(c)
<class 'str'>           #字符串
>>>d = b"abc"
>>>type(d)
>>><class 'bytes'>      #bytes类型
>>>l = []
>>>type(l)
<class 'list'>          #列表
>>>t = (1,2)
>>>type(t)
>>><class 'tuple'>      #元祖
>>>s = set([1,1,1,2])
>>>type(s)
<class 'set'>           #set
>>>s = {1,2,3,4}
>>>type(s)
<class 'set'>           #set也可以这样定义
>>>fs = frozenset([1,1,1,2])
>>>type(fs)
<class 'frozenset'>     #frozenset
>>>True
>>>type(True)
<class 'bool'>          #bool
>>>False
>>>type(False)
<class 'bool'>
>>> class P:pass        #类
... 
>>>p = P()              #类的实例化
>>>type(P)
<class 'type'>          #类定义
>>>type(p)
<class '__main__.P'>    #类实例

运算

>>>a = 1
>>>b = 2
>>>a + b        #加
3
>>>a - b        #减
-1
>>>a * b        #乘
2
>>>a / b        #除
0.5
>>>a // b       #整除
0
>>>a % b        #取余
1
>>>a ** b       #乘方
1
>>>pow(2,3)     #乘方
8
>>>import math      #引入math模块
>>>math.sqrt(b)     #开方
1.4142135623730951  
>>>math.floor(1/2)  #地板除
0
>>>math.ceil(1/2)   #天花板除
1
>>>round(0.3)   #四舍五入
0
>>>round(0.8)
1

字符串转换

python3:str类型是unicode字符,只能被encode(),简称ue
>>>s = "abc"
>>>type(s)
<class 'str'>       #unicode
>>>type(s.encode("utf-8"))
<class 'bytes'>
>>>type(s.encode("utf-8").decode("utf-8"))
<class 'str'>

python2:str类型是bytes字符,只能被decode()
>>> s = "abc"
>>> type(s)
<type 'str'>        #bytes
>>> type(s.decode("utf-8"))
<type 'unicode'>
>>> type(s.decode("utf-8").encode("utf-8"))
<type 'str'>

函数

>>>abs(-1)      #绝对值函数
1
>>>max([1,2,3]) #最大值函数,参数可以是1个序列或多个值,返回最大值
3
>>>min([1,2,3]) #最小值函数,参数可以是1个序列或多个值,返回最小值
>>>pow(2,3)     #乘方,2个参数就是乘方
8
>>> pow(2,3,5)  #乘方取余,3个参数就是前2个数乘方再和第3个数取余
3
>>>round(0.3)   #四舍五入,1个参数就是该参数四舍五入
0
>>>round(0.8)
1
>>> round(2.555556,3) #四舍五入,2个参数就是第1个参数保留第2个参数位四舍五入
2.556
>>>import math      #引入math模块
>>>math.sqrt(b)     #开方,返回平方根
1.4142135623730951  
>>>math.floor(1/2)  #地板除
0
>>>math.ceil(1/2)   #天花板除
1
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容