if ... elif... else: 他們垂直對齊,具有相同縮進,如果所有的測試都爲假的話,就執行else部分。
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 還可以連接兩個語句
>>> 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]