我正在為 Python 做一個練習課程,要求一個腳本來計算閏年。
閏年有以下條件:
- 必須是 4 的倍數
- 不能是 100 的倍數,除非它也是 400 的倍數。
嘗試1
year = int(input("Check this year "))
leapFourYears = year % 4
leapCentury = year % 100
leapFourCenturies = year % 400
if (leapFourYears == 0 & leapCentury != 0) | leapFourCenturies == 0:
print('leap year')
else:
print('not leap year')
這適用于例如 2000 年,但它錯誤地列印了例如 2016 年的“非閏年”。
我列印出每個條件,并且單獨地,它們按預期評估為真或假。但是,當我涉及 & 或 | 操作員,評估出錯。
我開始附加括號并遇到了這個正確的 if 陳述句:
嘗試 2
if ((leapFourYears == 0) & (leapCentury != 0)) | (leapFourCenturies == 0):
這行得通。
有人可以向我解釋 Python python 如何使用 & 和 | 決議多個條件嗎?沒有括號的運算子?Python 如何評估它使其適用于 2000 年而非 2016 年?
有沒有辦法在每個條件周圍沒有括號的情況下做到這一點?
謝謝!
Python 3.8.10
uj5u.com熱心網友回復:
您正在使用按位運算子,而不是邏輯運算子。代替
if ((leapFourYears == 0) & (leapCentury != 0)) | (leapFourCenturies == 0):
采用
if leapFourYears == 0 and leapCentury != 0 or leapFourCenturies == 0:
and優先于or.
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/429187.html
標籤:Python python-3.x
