目錄 | 上一節 (1.2 第一個程序) | 下一節 (1.4 字符串)python
本節討論數學計算。git
Python 有 4 種類型的數字:github
布爾型數字有兩個值:True
,False
。segmentfault
a = True b = False
在數值上,它們被計算成值爲 1
,0
的數。bash
c = 4 + True # 5 d = False if d == 0: print('d is False')
可是,不要像上面這樣寫代碼,這會很奇怪。ide
任意大小的有符號值,或者以任意數爲基數的有符號值。函數
a = 37 b = -299392993727716627377128481812241231 c = 0x7fa8 # Hexadecimal d = 0o253 # Octal e = 0b10001111 # Binary
經常使用操做:ui
x + y Add x - y Subtract x * y Multiply x / y Divide (produces a float) x // y Floor Divide (produces an integer) x % y Modulo (remainder) x ** y Power x << n Bit shift left x >> n Bit shift right x & y Bit-wise AND x | y Bit-wise OR x ^ y Bit-wise XOR ~x Bit-wise NOT abs(x) Absolute value
使用十進制或者指數表示法來指定浮點數的值:翻譯
a = 37.45 b = 4e5 # 4 x 10**5 or 400,000 c = -1.345e-10
使用浮點數表示 IEEE 754 標準的雙精度。這與 C 語言中的 double
類型相同。code
17 digits of precision
Exponent from -308 to 308
請注意,當表明小數時,浮點數是不精確的。
>>> a = 2.1 + 4.2 >>> a == 6.3 False >>> a 6.300000000000001 >>>
這不是 Python 的問題,而是 CPU 硬件上底層浮點硬件的問題。
經常使用操做:
x + y Add x - y Subtract x * y Multiply x / y Divide x // y Floor Divide x % y Modulo x ** y Power abs(x) Absolute Value
除了按位運算符以外,浮點數的運算符與整數的運算符是同樣的。
其它數學函數能夠在 math
中找到。
import math a = math.sqrt(x) b = math.sin(x) c = math.cos(x) d = math.tan(x) e = math.log(x)
下面的比較/關係運算符能夠應用於數字:
x < y Less than x <= y Less than or equal x > y Greater than x >= y Greater than or equal x == y Equal to x != y Not equal to
可使用 and
, or
,not
組成更復雜的布爾表達式。
這裏有一些例子:
if b >= a and b <= c: print('b is between a and c') if not (b < a or b > c): print('b is still between a and c')
類型名能夠被用來將其它數據轉換爲數字。
a = int(x) # Convert x to integer b = float(x) # Convert x to float
試試下面這些操做:
>>> a = 3.14159 >>> int(a) 3 >>> b = '3.14159' # It also works with strings containing numbers >>> float(b) 3.14159 >>>
提醒:這些習題假定你正在 practical-python/Work
目錄中操做,具體在 mortgage.py
文件。
戴夫決定從 Guido 的抵押貸款、股票投資和比特幣交易公司得到 50 萬美圓的 30 年期固定利率抵押貸款。利率是 5%,每個月還款額是 2684.11 美圓。
下面這個程序用於計算戴夫在抵押期內須要支付的總金額:
# mortgage.py principal = 500000.0 rate = 0.05 payment = 2684.11 total_paid = 0.0 while principal > 0: principal = principal * (1+rate/12) - payment total_paid = total_paid + payment print('Total paid', total_paid)
輸入該程序並執行,你應該會獲得答案爲 966,279.6
。
假設戴夫在抵押期的前 12 個月每個月額外支付 1000 美圓。
修改程序以包含這部分額外的付款,而且輸出已支付的總金額以及所需的月數。
當你執行這個新程序時,它應該報告 342 個月的總付款額是 929,965.62
。
修改程序,以即可以更通常地處理額外的付款信息。作到這一點,以便用戶能夠設置下面這些變量:
extra_payment_start_month = 61 extra_payment_end_month = 108 extra_payment = 1000
使程序查看這些變量,並適當地計算總付款額 。若是戴夫從抵押期的第五年開始,每個月額外支付 1000 每個月並支付 4 年,那麼他將要支付多少?
修改程序,使其顯示迄今爲止支付的月數,支付的總金額和剩餘的本金。輸出看起來應該像下面這樣:
1 2684.11 499399.22 2 5368.22 498795.94 3 8052.33 498190.15 4 10736.44 497581.83 5 13420.55 496970.98 ... 308 874705.88 3478.83 309 877389.99 809.21 310 880074.1 -1871.53 Total paid 880074.1 Months 310
使用該程序時,請修復程序以糾正發生在上個月的超額支付。
int()
函數和 float()
函數能夠將其它類型的數據轉換爲數字類型。示例:
>>> int("123") 123 >>> float("1.23") 1.23 >>>
考慮到這一點,你可否解釋下面這種行爲?
>>> bool("False") True >>>