作者CMJ0121 (不要偷 Q)
看板Python
标题Re: [问题] 请问范例
时间Fri Sep 11 07:32:39 2020
※ 引述《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://webptt.com/cn.aspx?n=bbs/Python/M.1599780763.A.3DA.html