(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)
           #整形
>>>b = 1.0
>>>type(b)
         #浮点型
>>>e = 1 + 1j
>>>type(e)
       #复数
>>>c = "abc"
>>>type(c)
           #字符串
>>>d = b"abc"
>>>type(d)
>>>      #bytes类型
>>>l = []
>>>type(l)
          #列表
>>>t = (1,2)
>>>type(t)
>>>      #元祖
>>>s = set([1,1,1,2])
>>>type(s)
           #set
>>>s = {1,2,3,4}
>>>type(s)
           #set也可以这样定义
>>>fs = frozenset([1,1,1,2])
>>>type(fs)
     #frozenset
>>>True
>>>type(True)
          #bool
>>>False
>>>type(False)

>>> class P:pass        #类
... 
>>>p = P()              #类的实例化
>>>type(P)
          #类定义
>>>type(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)
       #unicode
>>>type(s.encode("utf-8"))

>>>type(s.encode("utf-8").decode("utf-8"))


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

>>> type(s.decode("utf-8").encode("utf-8"))

函数

>>>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

你可能感兴趣的:((2)变量类型、运算和字符串编码)