[英]in Python does 'or not' has 'not' precencence or 'or' precedence?
第一次在這里尋求幫助。
我通過 Kaggle 的 Python 練習和布爾部分有這個例子:
prepared_for_weather = have_umbrella or rain_level < 5 and have_hood or not rain_level > 0 and is_workday
他們說為了使代碼更具可讀性,它有助於以這種方式使用括號:
prepared_for_weather = have_umbrella or (rain_level < 5 and have_hood) or not (rain_level > 0 and is_workday)
我很困惑為什么(考慮到運算符在 not、and、or 中的優先級順序)在表達式末尾 the and after rain_level > 0的優先級高於not之前的優先級。
是不是因為not應該被考慮為“或不是” ,所以比and的優先級低?
我希望這已經足夠清楚了,謝謝!
閱讀 Python 的文檔后發現優先順序不是,並且,或者我預計not just before rain_level > 0 的優先級高於 rain_level > 0 之前和之后的優先級。
如文檔中所述, not x
優先於and
建議的帶有大括號“為了可讀性”的表達式不等同於第一個,例如
have_umbrella = False
have_hood = False
is_workday = False
rain_level = 3
# first
prepared_for_weather = have_umbrella or rain_level < 5 and have_hood or not rain_level > 0 and is_workday
print(prepared_for_weather)
# Kaggle's
prepared_for_weather = have_umbrella or (rain_level < 5 and have_hood) or not (rain_level > 0 and is_workday)
print(prepared_for_weather)
# mine from comments
prepared_for_weather = have_umbrella or rain_level < 5 and have_hood or ((not rain_level > 0) and is_workday)
print(prepared_for_weather)
output
False
True
False
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.