Python 練習問題4

Python 100例

問題:ある年・月・日を入力し、その日がその年の何日目かを判定します。

プログラム分析:3月5日を例にすると、まず最初の2ヶ月の日数を合計し、それに5日を加えるとその年の何日目かがわかります。特殊なケースとして、うるう年であり、入力した月が2より大きい場合、1日余分に加えることを考慮する必要があります:

プログラムのソースコード:

例

#!/usr/bin/python3 year = int(input('year:\n')) month = int(input('month:\n')) day = int(input('day:\n')) months = (0,31,59,90,120,151,181,212,243,273,304,334) if 0 < month <= 12: sum = months[month - 1] else: print ('data error') sum += day leap = 0 if (year % 400 == 0) or ((year % 4 == 0) and (year % 100 != 0)): leap = 1 if (leap == 1) and (month > 2): sum += 1 print ('it is the %dth day.' % sum)

上記の例の出力結果は次のとおりです:

year:
2015
month:
6
day:
7
it is the 158th day.

Python 100例

その他の拡張