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
>>>