iT邦幫忙

2024 iThome 鐵人賽

DAY 4
0
Python

30天導讀 Python Software Foundation 官方翻譯文件系列 第 4

Day 3 -把 Python 當作計算機使用(數字篇)~導讀 Python Software Foundation 教學文件

  • 分享至 

  • xImage
  •  

數字 (Number)

直譯器如同一台簡單的計算機:你可以輸入一個 expression(運算式),它會寫出該式的值。Expression 的語法可以使用:運算子 +、-、* 和 / 可以用來執行運算;括號 () 可以用來分群。例如:

>>>
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 型態。我們將在之後的教學中看到更多數字相關的型態。

除法 (/) 永遠回傳一個 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 中,計算冪次 (powers) 可以使用 ** 運算子 [1]:

>>>
5 ** 2  # 5 squared
25
2 ** 7  # 2 to the power of 7
128

等於符號 (=) 可以用於為變數賦值。賦值完之後,在下個指示字元前並不會顯示任何結果:

>>>
width = 20
height = 5 * 9
width * height
900

如果一個變數未被「定義 (defined)」(即變數未被賦值),試著使用它時會出現一個錯誤:

>>>
n  # try to access an undefined variable
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'n' is not defined

浮點數的運算有完善的支援,運算子 (operator) 遇上混合的運算元 (operand) 時會把整數的運算元轉換為浮點數:

>>>
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 亦內建支援複數 (complex numbers),並使用 j 和 J 後綴來指定虛數的部份(即 3+5j)。


上一篇
Day 2 -使用 Python 直譯器-導讀 Python Software Foundation 官方文件
下一篇
Day 4 -把 Python 當作計算機使用(文字篇)~導讀 Python Software Foundation 教學文件
系列文
30天導讀 Python Software Foundation 官方翻譯文件12
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言