目錄
整數(如,2、4、20?)的類型是?int,帶小數(如,5.0、1.6?)的類型是?float。
Python 用?**?運算符計算乘方?1:
等號(=)用于給變量賦值。
解釋器像一個簡單的計算器:你可以輸入一個表達式,它將給出結果值。 表達式語法很直觀:運算符?+
,?-
,?*
?和?/
?可被用來執行算術運算;圓括號 (()
) 可被用來進行分組。 例如:
>>>
>>> 2 + 2 4 >>> 50 - 5*6 20 >>> (50 - 5*6) / 4 5.0 >>> 8 / 5 # division always returns a floating point number 1.6
整數(如,2
、4
、20
?)的類型是?int,帶小數(如,5.0
、1.6
?)的類型是?float。
本教程后半部分將介紹更多數字類型。
除法運算 (/
) 總是返回浮點數。 如果要做?floor division?得到一個整數結果你可以使用?//
?運算符;要計算余數你可以使用?%
:
>>>
>>> 17 / 3 # classic division returns a float 5.666666666666667 >>> >>> 17 // 3 # floor division discards the fractional part 5 >>> 17 % 3 # the % operator returns the remainder of the division 2 >>> 5 * 3 + 2 # floored quotient * divisor + remainder 17
Python 用?**
?運算符計算乘方?1:
>>>
>>> 5 ** 2 # 5 squared 25 >>> 2 ** 7 # 2 to the power of 7 128
等號(=
)用于給變量賦值。
賦值后,下一個交互提示符的位置不顯示任何結果:
>>>
>>> width = 20 >>> height = 5 * 9 >>> width * height 900
如果變量未定義(即,未賦值),使用該變量會提示錯誤:
>>>
>>> n # try to access an undefined variable Traceback (most recent call last):File "<stdin>", line 1, in <module> NameError: name 'n' is not defined
Python 全面支持浮點數;混合類型運算數的運算會把整數轉換為浮點數:
>>>
>>> 4 * 3.75 - 1 14.0
交互模式下,上次輸出的表達式會賦給變量?_
。把 Python 當作計算器時,用該變量實現下一步計算更簡單,例如:
>>>
>>> tax = 12.5 / 100 >>> price = 100.50 >>> price * tax 12.5625 >>> price + _ 113.0625 >>> round(_, 2) 113.06
最好把該變量當作只讀類型。不要為它顯式賦值,否則會創建一個同名獨立局部變量,該變量會用它的魔法行為屏蔽內置變量。
除了?int?和?float,Python 還支持其他數字類型,例如?Decimal?或?Fraction。Python 還內置支持?復數,后綴?j
?或?J
?用于表示虛數(例如?3+5j
?)。