我正在为我的CS课创建一个年龄计算器,我需要添加一个公式,在其中显示某人的年龄和月份。
仅通过now.year -year来计算year公式很简单,但是month则要复杂得多,因为python会将两个月之间的距离计算为负数。例如,如果您输入的月份是2月,而不是说您距生日8个月,则表示您距生日-3个月。
import datetime
now = datetime.datetime.now()
print ("Current year:", now.year)
print ("Current month:", now. month)
year = int(input("What year were you born in? "))
month = int(input("What month were you born in? "))
agemonth = month - now.month
age = now.year - year
print("Your age is", age)
if age >= 16:
print("You are old enough to drive")
else:
print("You are not old enough to drive")
if age >= 21:
print("You are old enough to drink")
else:
print("You are not old enough to drink")
理想情况下,如果您输入2月,程序会打印出您距离生日8个月,而不是距生日3个月
答案 0 :(得分:1)
尝试使用模运算符:
agemonth = (month - now.month) % 12
在一月和二月出生的时候,减法为-1,但是12的余数就是11,这就是我们想要的。
答案 1 :(得分:0)
要照顾负面的几个月,您需要做两件事
%12
,因此-4
变为8 if
语句考虑到这两个更改,代码变为
import datetime
now = datetime.datetime.now()
print ("Current year:", now.year)
print ("Current month:", now. month)
year = int(input("What year were you born in? "))
month = int(input("What month were you born in? "))
agemonth = now.month - month
age = now.year - year
#If months are negative
if agemonth < 0:
#Take modulo 12 of agemonth to make it positive
agemonth = agemonth%12
#Subtract 1 from year
age = age - 1
print("Your age is ", age, "years and", agemonth, 'months')
#3 If statements based on ages
if age <= 16:
print("You are not old enough to drive")
print("You are not old enough to drink")
elif 16 < age < 21:
print("You are old enough to drive")
print("You are not old enough to drink")
else:
print("You are old enough to drive")
print("You are old enough to drink")
可能的输出是
Current year: 2019
Current month: 5
What year were you born in? 1991
What month were you born in? 1
Your age is 28 years and 4 months
You are old enough to drive
You are old enough to drink
Current year: 2019
Current month: 5
What year were you born in? 2005
What month were you born in? 8
Your age is 13 years and 9 months
You are not old enough to drive
You are not old enough to drink
Current year: 2019
Current month: 5
What year were you born in? 2001
What month were you born in? 1
Your age is 18 years and 4 months
You are old enough to drive
You are not old enough to drink
答案 2 :(得分:0)
考虑到您所说的某人在2月有生日的事实,输出应表明他们的生日在8个月后,正确的公式应为:
agemonth = (month-now.month-1)%12
#month = 2, now.month = 5. Thus agemonth = 8
这将始终为您提供所需的输出。
答案 3 :(得分:0)
from datetime import date
year = int(input("What year were you born in? "))
month = int(input("What month were you born in? "))
today = date.today()
age = today.year - year
agemonth = today.month - month
totmonth = 0
if agemonth >= 0:
totmonth = agemonth
else:
agemonth = 12 + agemonth
age -= 1
print "age is" , age,"years and", agemonth,"months"
if age <= 16:
print("You are not old enough to drive")
print("You are not old enough to drink")
elif 16 < age < 21:
print("You are old enough to drive")
输出:
您出生于哪一年? 1999
您出生在哪个月份? 7
年龄是19岁11个月
您已经可以开车
你还没有喝酒的年龄