if文とand/or用法の拡張
1744 ワード
if ... elif... else:垂直に整列し、同じインデントを持ち、すべてのテストが偽物であればelse部分を実行します.
if/else三元表現A=Y if X else ZはA=((X and Y)or Z)に等しい.まず,YとZはいずれも値であるため,あるいは他のタイプであることが明らかになった.だからデフォルトは本当です.具体的なand/orの操作は以下の真値テストを参照してください
真値テスト
1:ゼロ以外の数値または空以外のオブジェクトはすべて真です.
2:数字0、空のオブジェクト[]、および特殊なオブジェクトNoneはすべて偽と見なされます
3:==,>=などのテストでブール値が返されます
4:Trueは1を表し、Falseは0を表し、T、Fはすべて大文字でなければならないことに注意してください.
and/orの使い方
1:andとorは操作のオブジェクトを返して、orは最初が本当のオブジェクトで、andは最初が偽物のオブジェクトを返します
2:x=A or default Aが真(または空でない)の場合、XをAに設定します.そうでない場合はdefaultになります.
4:and/or同時に条件の接続にも使用できます
5:andとorは2つの文を接続することもできます
if/else三元表現A=Y if X else ZはA=((X and Y)or Z)に等しい.まず,YとZはいずれも値であるため,あるいは他のタイプであることが明らかになった.だからデフォルトは本当です.具体的なand/orの操作は以下の真値テストを参照してください
>>> branch = {'spam': 1.24,
... 'ham': 1.99,
... 'egg': 0.33}
>>> print(branch.get('spam', 'bad choice')) # get ,
1.24
>>> if choice in branch:
... print(branch[choice])
... else:
... print('bad choice') # switch
真値テスト
1:ゼロ以外の数値または空以外のオブジェクトはすべて真です.
2:数字0、空のオブジェクト[]、および特殊なオブジェクトNoneはすべて偽と見なされます
3:==,>=などのテストでブール値が返されます
4:Trueは1を表し、Falseは0を表し、T、Fはすべて大文字でなければならないことに注意してください.
>>> while true:
... print('hello world')
... break
...
NameError: name 'true' is not defined
and/orの使い方
1:andとorは操作のオブジェクトを返して、orは最初が本当のオブジェクトで、andは最初が偽物のオブジェクトを返します
2:x=A or default Aが真(または空でない)の場合、XをAに設定します.そうでない場合はdefaultになります.
4:and/or同時に条件の接続にも使用できます
5:andとorは2つの文を接続することもできます
>>> 0 or [] and 5
[]
>>> 2 or 4,6 or 9
(2, 6)
>>> x = 0 or 6
>>> x
6
>>> if 1>0 and 5<6:
... print("true")
...
true
>>> [print(i) and i for i in range(3)]
0
1
2
[None, None, None] # print() None, 3 None
>>> [i and print(i) for i in range(3)]
1
2
[0, None, None] # i=0 , 0
>>> [print(i) or i for i in (2,3,4)] # , ,
2
3
4
[2, 3, 4]