0
我期望下面的代碼正常工作,因爲第一個條件如果爲false,但它通過IndexError: string index out of range
。我錯過了什麼?Python條件評估
a = False
sample_strign = 'test'
if (a == True) & (sample_strign[7] == 's'):
print('foo')
我期望下面的代碼正常工作,因爲第一個條件如果爲false,但它通過IndexError: string index out of range
。我錯過了什麼?Python條件評估
a = False
sample_strign = 'test'
if (a == True) & (sample_strign[7] == 's'):
print('foo')
&
是一個按位運算符。如果您希望解釋器將邏輯「短路」,請使用邏輯運算符and
。
if a and (sample_strign[7] == 's'):
sameple_strign
沒有這將引發一個異常第七指數,你應該使用類似:
if a and len(sample_strign) > 7:
if sample_strign[7] == 's':
print('foo')
'&'是位運算符,並且不短路。 – user2357112
此外,檢查只是'a'甚至'a是真的'比'a == True'更Pythonic –
[布爾運算符vs位運算符]的可能重複(https://stackoverflow.com/questions/3845018/布爾運算符-VS-按位運算符) –