考え方
年齢は、現在の西暦年から生まれた時の西暦年を引いて求める。(これが基本)
例)1984年生まれ、現在2020年
2020年 - 1984年 = 36歳
ただし、以下の条件の場合、年齢が1減ることになる。
【条件1】
生まれ月が今月より大きい場合は、年齢を1減らす。
例)12月生まれ、今月は11月
36歳 - 1歳 = 35歳
【条件2】
もし、生まれ月と今月が同じなら、生まれた日と今日の日を比べて、生まれた日の方が大きいなら年齢を1減らす。
例)11月30日生まれ、今日は11月20日
36歳 - 1歳 = 35歳
Pythonスクリプト
ima_nansai.py
# 生年月日から現在の年齢を求めて表示する import datetime # 生年月日を入力 print("生年月日を入力してください") print("年?(西暦) ", end="") myYear = int(input()) print("月? ", end="") myMonth = int(input()) print("日? ", end="") myDay = int(input()) # 今日の年月日を取得 today = datetime.date.today() year = today.year month = today.month day = today.day # 年齢を計算する age = year - myYear if month < myMonth: age -= 1 elif month == myMonth: if day < myDay: age -= 1 print("今、" + str(age) + "才ですね")
実行イメージ
生年月日を入力してください
年?(西暦) 1984 [Enter]
月? 12 [Enter]
日? 13 [Enter]
今、35才ですね
新型コロナウイルスは何歳だろう?
コメント