Python 数字类型
Python支持四种不同的数字类型:
- int(有符号整型)
- float(浮点型)
- complex(复数)
如:
x = 8 # int
y = 9.8 # float
z = 5j # complex
Int (整型)
整型可正可负,不带小数,且没有长度限制,如:
x = 8
y = 85656222554887711
z = -8255522
print(type(x))
print(type(y))
print(type(z))
结果为:
>>> x = 8
>>> y = 85656222554887711
>>> z = -8255522
>>>
>>> print(type(x))
<class 'int'>
>>> print(type(y))
<class 'int'>
>>> print(type(z))
<class 'int'>
>>>
Float (浮点数)
浮点数可正可负,带一位或多位小数,如:
x = 1.80
y = 8.0
z = -38.59
print(type(x))
print(type(y))
print(type(z))
结果为:
>>> x = 1.80
>>> y = 8.0
>>> z = -38.59
>>>
>>> print(type(x))
<class 'float'>
>>> print(type(y))
<class 'float'>
>>> print(type(z))
<class 'float'>
>>>
浮点数也可以是科学计数法形式的数字,即以字母 e
代表 10 的幂,如:
x = 85e3
y = 18E4
z = -88.7e100
print(type(x))
print(type(y))
print(type(z))
结果为:
>>> x = 85e3
>>> y = 18E4
>>> z = -88.7e100
>>>
>>> print(type(x))
<class 'float'>
>>> print(type(y))
<class 'float'>
>>> print(type(z))
<class 'float'>
>>>
Complex (负数)
复数由实部和虚部组成,虚部带有字母 j 标记,如:
x = 7 + 8j
y = 5j
z = -5j
print(type(x))
print(type(y))
print(type(z))
结果为:
>>> x = 7 + 8j
>>> y = 5j
>>> z = -5j
>>>
>>> print(type(x))
<class 'complex'>
>>> print(type(y))
<class 'complex'>
>>> print(type(z))
<class 'complex'>
>>>
可以使用 int(),float(),complex() 作类型转化,如:
x = 6 # int
y = 4.8 # float
z = 3j # complex
#convert from int to float:
a = float(x)
#convert from float to int:
b = int(y)
#convert from int to complex:
c = complex(x)
print(a)
print(b)
print(c)
print(type(a))
print(type(b))
print(type(c))
结果为:
>>> x = 6 # int
>>> y = 4.8 # float
>>> z = 3j # complex
>>>
>>> #convert from int to float:
... a = float(x)
>>>
>>> #convert from float to int:
... b = int(y)
>>>
>>> #convert from int to complex:
... c = complex(x)
>>>
>>> print(a)
6.0
>>> print(b)
4
>>> print(c)
(6+0j)
>>>
>>> print(type(a))
<class 'float'>
>>> print(type(b))
<class 'int'>
>>> print(type(c))
<class 'complex'>
>>>
随机数
Python 没有 random() 函数来产生随机数,但是提供了一个内置模块。
import random
print(random.randrange(2,8))
结果为:
>>> import random
>>> print(random.randrange(2,8))
6
>>>