<--/> Fork me on GitHub

类型转换--number之间互转

类型转换--number之间互转

1.强制转换

  强制转换是人为添加转换,实现类型的转换

  int() float() bool() complex()
  默认创建一个该数据类型的值
  res = int()
  res = float()
  res = bool()
  res = complex()

var1 = 13
var2 = 13.789
var3 = True
var4 = 5-7j
var5 = "9988"
var6 = "abcd4567"


# (1) int 强制转换成整型
res = int(var2) # 13
res = int(var3) # False => 0 True => 1
# res = int(var4) error                 #复数带有虚数,不可以转换成int类型
res = int(var5) # 9988
# res = int(var6) error             #var6含有字母,无法转换成int类型
print(res , type(res))


# (2) float 强制转换成浮点型
res = float(var1) # 13.0
res = float(var3) # True => 1.0 False => 0.0
res = float(var5) # 9988.0
print(res , type(res))


# (3) complex 强制转换成复数
res = complex(var1) # 13 + 0j
res = complex(var2) # 13.789 + 0j
res = complex(var3) # False => 0j True => 1+0j
res = complex(var5) # 9988 + 0j
# res = complex(var6) error
print(res , type(res))


# (4) bool 强制转换成布尔型 (***)
"""
bool类型为假的十种情况
0 , 0.0 , False , 0j , '',[],(),set(),{},None
"""
res = bool(None)
print(res , type(res))

# None 是python的关键字,代表空的,什么也没有,一般用来做初始化操作
a1 = None
b1 = None

3.自动类型转换

自动转换是指不需要人为转换,在计算的时候的计算机自动完成的转换

精度从低向高进行转换 : bool -> int -> float -> complex
自动类型转换,默认从低精度向高精度进行转换(从低到高)

# 1.bool + int
res = True + 100 # 1 + 100 
print(res)

# 2.bool + float
res = True + 4.15 # 1.0 + 4.15
print(res)

# 3.bool + complex
res = True + 3-6j # 1+0j + 3 - 6j
print(res)

# 4.int + float
res = 5 + 3.48 # 5.0 + 3.48
print(res)

# 5.int + complex
res = 10 + 4-3j # 10 + 0j + 4 - 3j
print(res)

# 6.float + complex
res = 5.68 + 5-100j # 5.68+0j + 5 - 100j
print(res)

 

 

posted @ 2020-08-02 10:58  sonder  阅读(222)  评论(0)    收藏  举报
1