Re: [問題] 請問範例
※ 引述《pttnewborn (pttnewborn)》之銘言:
: 大家好:
: 剛學Python,書上有個範例如下
: -------------------------------------
: condiiton = 10
: while condiiton:
: print(condiiton)
: condiiton -= 1
: -------------------------------------
: 這範例是可以跑出結果來的(10,9,8,7,6....)
: 我的問題是while 後面不是要有判斷式嗎?
: 比如while condiiton>0:
: 因為他沒寫判斷式,結果跟condition>0效果一樣,
: 還是他是預設>0??
: 謝謝!
睡不著回一下:
根據 Python 語法 [0] while-stmt 是 "while" assignment_expression ":" 這種形式
其中 assignment_expression 可以是 [ identifier ":=" ] expression
如果你不賦值 後面就會是一個表達式
根據文件中表示:根據 while 後面結果判斷是否為 True/False 來決定執行那段程式碼
接著就跳到 PEP 308[1] 來決定條件表達式是什麼 但是你的問題是 condiiton 是一個變數
問題就變成變數本身如何判斷是 True 還是 False 這就跳到 Python 的 Truth Value Testing [2]
object 被判斷為 True 除非
- 有定義 __bool__ 而且回傳 False
- 有定義 __len__ 而且回傳 0
- 直接就是 False 或者 None
- 各種零,像是 0, 0.0, 0j, Decimal(0), Fraction(0, 1)
- 空序列、集合
## 給 End 的人 ##
對 Python 來說 空的東西就是 False
空的定義為:__len__() 為 0 或者 Python 內建的空元素 (像是 0 或者空字串等)
如果你自己定義 __bool__() 是 False 那也就會是 False
[0]: https://docs.python.org/3/reference/compound_stmts.html#grammar-token-while-stmt
[1]: https://www.python.org/dev/peps/pep-0308/
[2]: https://docs.python.org/3/library/stdtypes.html#truth
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 106.1.229.246 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Python/M.1599780763.A.3DA.html
討論串 (同標題文章)
Python 近期熱門文章
PTT數位生活區 即時熱門文章