数字类型

三种数字类型

  1. int 整型数字,比如2015
  2. float 浮点型数字,比如3.14
  3. complex 复数,比如3+2j

整型

整型(int)字面量在Python中属于int类。

1
2
3
>>> i = 100
>>> i
100

数字可以进行各种运算,如:

1
123 + 345

还可以使用数学模块进行更高级的运算,如产生随机数等等:

1
2
import random
print(random.random())

浮点类型

浮点数(float)是指有小数点的数字。

1
2
3
>>> f = 12.3
>>> type(f)
<class 'float'>

复数

复数(Complex number) 由实数和虚数两部分构成,虚数用j表示。我们可以这样定义一个复数:

1
2
3
>>> x = 2+3j
>>> type(x)
<class 'complex'>

类型转化

可以使用int()float()str()进行类型转化。

1
2
3
4
5
a = "123"
print(type(int(a)))
print(type(float(a)))
b = 123.123
print(type(str(b)), str(b))

小结

  1. Python中的数字类型有整数、浮点数和复数三种。
  2. 可以使用type()方法查询对象的类型。
  3. 可将数字转化为字符串,也可将仅包含数字的字符串转为数字。