Zerojudge 基礎題庫a004 文文的求婚 (Python)
西元年被4整除且不被100整除,或被400整除者即為閏年
=> year % 4 == 0 and year % 100 != 0 or year % 400 == 0
如果是True就是閏年
False 則是平年
對!就這樣~
Python 程式碼:
1 2 3 4 5 6 7 8 9 10 | while 1: try: x = int(input()) except: break if x % 4 == 0 and x % 100 != 0 or x % 400 == 0: print("閏年") else: print("平年") |
作者已經移除這則留言。
回覆刪除不好意思請教一下前面的try跟except 區塊是什麼?
回覆刪除因為沒有給測試資料的數量
刪除也就是不知道要執行input()多少次
這時候就必然執行的while迴圈一直讀資料
如果資料讀完了還執行input()
程式就會拋出exception (raise exception)
try:
//do something
except some_exception:
會接住try區塊拋出的, 類型為"some_exception" 的 exception
也就是說
在try區塊內的input()讀不到資料拋出拋出exception後
會被面的except接住
進而執行break跳出while迴圈
就降
另外
如果沒有指定要接住哪類型的exception
最好不要寫
except:
而是
except Exception:
如果只寫except而沒有指明要接住哪一種exception的話
會連KeyboardInterrupt都接住
進而使你無法以ctrl+c終止程式的執行
所以如果你在自己的電腦執行他寫的程式的話
會出現無法終止程式的小問題