# 简简单单五分钟，教你搞定Python中数值类型的基础细节

230

**前面介绍了程序的流程控制，除此之外，你还需要在程序中表达数据，而为了表达数据，Python提供了各种数据类型。**本文将介绍内置类型-Number，它用于表示数值类型，比如整数或实数。

# 如何定义数值类型的变量

Python内置了许多数值类型，这些类型中，常用的数值类型有int和float。你可以通过以下方式创建一个数值变量：

``````var1 = 1
var2 = 10.0
``````

var1是int类型的变量，它对应数学中的整数，它的范围是(-inf, inf)，即无穷大，下面的例子说明了这一点：

``````>>> a = 100
>>> type(a)
<class 'int'>

>>> b = 10**1000
>>> b
10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
>>> type(b)
<class 'int'>
``````

var2是float类型的变量，它对应数学中的实数，你可以通过运行下面指令来查看它的范围:

``````>>> sys.float_info
sys.float_info(max=1.7976931348623157e+308, max_exp=1024, max_10_exp=308, min=2.2250738585072014e-308, min_exp=-1021, min_10_exp=-307, dig=15, mant_dig=53, epsilon=2.220446049250313e-16, radix=2, rounds=1)
``````

``````>>> af = 1.7976931348623157e+309
>>> af
inf
>>> af = 1.7976931348623157e+308
>>> af
1.7976931348623157e+308
``````

``````>>> baf = True
>>> type(baf)
<class 'bool'>
>>> baf + 2
3
``````

# 数值类型的转换

``````>>> str1 = str(3)
>>> str2 = str(3.14)
>>> str1
'3'
>>> str2
'3.14'
>>> type(str1)
<class 'str'>
``````

``````>>> var1 = int('1')
>>> var2=float('10.0')
>>> var1
1
>>> type(var1)
<class 'int'>
``````

``````>>> var1 = int(10.02)
>>> var2 = float(var1)
>>> type(var1)
<class 'int'>
>>> type(var2)
<class 'float'>
``````

# 数值类型的操作

``````>>> var1 = 1 + 2
>>> var2 = 1 + 2.0
>>> type(var1)
<class 'int'>
>>> type(var2)
<class 'float'>
>>> var1
3
>>> var2
3.0
``````

``````>>> a = 2
>>> b = 3.0
>>> is_a_great_than_b = a > b
>>> print("a > b") if is_a_great_than_b else  print("a <= b")
a <= b
>>> type(is_a_great_than_b)
<class 'bool'>
``````

``````>>> a = 3
>>> b = 6.9
>>> a_and_b = a and b
>>> a_or_b = a or b

>>> a_and_b
6.9
>>> type(a_and_b)
<class 'float'>

>>> a_or_b
3
>>> type(a_or_b)
<class 'int'>
``````