讓我們舉個例子:
我想檢查變數s是否是長度等于或小于 3 的字串。我嘗試了以下操作:
if (not isinstance(s,str)) | (len(s)>3) :
print("The value of s is not correct : must be a string, with length equal or less than 3")
但這是不正確的,因為無論第一個條件的結果如何,代碼都會考慮第二個條件。例如,對于s = 2,代碼回傳錯誤:
object of type 'int' has no len()
我本以為,由于第一個條件是True,因此不會考慮該行的其余部分。我怎樣才能讓代碼運行直到True達到第一個條件?
uj5u.com熱心網友回復:
|是按位或。請改用關鍵字or。
正如您在問題中正確提到的那樣, or 會短路,因此如果s不是字串,則第二部分將不會評估,從而防止嘗試應用于len非字串物件的錯誤。
if not isinstance(s, str) or len(s) > 3:
print("The value of s is not correct : must be a string, with length equal or less than 3")
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/537921.html
