python强制类型转换和自动类型转换

一. 强制类型转换:Number (int float complex bool )

----------------------------------------------

var1 = 3
var2 = 5.67
var3 = "123"
var4 = 5+6j
var5 = "abc"
var6 = True
var7 = False

------------------------------------------------

1.1int的强制转换

可以转换为整型.浮点型.布尔型.纯数字字符串

res = int(var2)
res = int(var3)
res = int(var6) # True =>  1
res = int(var7) # False => 0
# res = int(var4) error
# res = int(var5) error
print(res , type(res))

1.2float的强制转换

可以转换为整型.浮点型.布尔型.纯数字字符串

res = float(var1)
res = float(var3)
res = float("123.456")
res = float(var6) # True  => 1.0
res = float(var7) # False => 0.0

print(res , type(res))

1.3 complex的强制转换

可以转换为整型 浮点型 布尔型 纯数字字符串 复数

res = complex(var1)
res = complex(var2)
res = complex(var3)
# res = complex(var5) error
res = complex(var6) # True => 1+0j
res = complex(var7) # False => 0j
print(res , type(res)) # 3+0j

1.3 bool的强制转换 ****************

"""
没有数据类型的限制,可以转换一切数据类型;
bool => True 或者 False
布尔型为假的十种情况:
Number : 0  ,  0.0  , 0j , False
容器   : '' , [] , () , set() , {}
关键字 : None (代表空的,什么也没有,一般用来对变量做初始化操作的)
"""
res = bool( None )
print(res , type(res)) 


# 初始化变量 , 使用None
a = None
b = None

二.自动类型转换 Number

精度从高到低

bool-->int-->float-->complex

自动类型转换原则: 把低精度的数据向高精度进行转换

# bool + int
res = True + 100 # 1 + 100 => 101
print(res , type(res))

# bool + float
res = True + 4.5 # 1.0 + 4.5 => 5.5
print(res , type(res))

# bool + complex
res = True + 6+3j # 1+0j  +  6+3j => 7 + 3j
print(res , type(res))

# int + float
res = 120 + 3.14 # 120.0 + 3.14
print(res , type(res))

# int + complex
res  =100 + 4-3j # 100 + 0j +4-3j
print(res , type(res))

# float + complex
res = 5.67 + 3+3j # 5.67 + 0j + 3 + 3j
print(res , type(res))

# 精度损耗 (写程序时,不要用小数做比较的条件,会导致结果不准确,一般系统会把小数位截取15~18位而产生数据的误差)
res = 0.1+0.2 == 0.3
res = 4.1+4.2 == 8.3
print(res)
原文地址:https://www.cnblogs.com/whc6/p/14012057.html