我制作了这个程序,根据你的生日找出你的年龄。
print"Let's find your exact age using your birthday!"
d1=int(input("Enter your date of birth:-"))
d1=int(d1)
m1=int(input("Enter your month of birth:-"))
m1=int(m1)
y1=int(input("Enter your year of birth:-"))
y1=int(y1)
d2=int(input("Enter todays date:-"))
d2=int(d2)
m2=int(input("Enter the month we are in:-"))
m2=int(m2)
y2=int(input("Enter the year right now:-"))
y2=int(y2)
rd= y2-y1
md= abs(m2-m1)
dd= abs(d2-d1)
if md > 0:
print("You will be", rd,"years old in",md, "months and", dd,"days!")
else:
print("You will be", rd,"years old in", dd, "days")
if dd > 0:
print("You will be", rd,"years old in",md, "months and", dd,"days!")
else:
print("You will be", rd,"years old in",md,"months.")
if (md > 0 and
dd > 0):
print("You will be", rd,"years old in",md, "months and", dd,"days!")
else:
print("You are",rd, "years old! And it's your birthday! Happy Birthdaay!!!")
我想制作最后的if-else条件打印"生日快乐"只有当md和dd都小于0时才会发生,但是由于之前的条件,输出的形式是:
('You will be', 16, 'years old in', 0, 'days')
('You will be', 16, 'years old in', 0, 'months.')
('You are', 16, "years old! And it's your birthday! Happy Birthdaay!!!")
我如何纠正这个?
答案 0 :(得分:0)
你必须重新考虑一下你的逻辑。这是一种做你想做的事情的方法:
if md == 0 and dd == 0:
print "You are", rd, "years old! And it's your birthday! Happy Birthdaay!!!"
elif md == 0:
print "You will be", rd, "years old in", dd, "days"
elif dd == 0:
print "You will be", rd, "years old in", md, "months"
else:
print "You will be", rd, "years old in", md, "months and", dd, "days!"
这使用elif
,它是else
和if
的组合:它仅在前面的if
(或elif
)条件为false时才会执行而且它自己的条件是真的。在上面的代码中,我们保证只打印一条消息。
旁注:正如您可能已经注意到的那样,此程序无法计算某人生日的时间。您必须为rd
,md
和dd
执行一些更复杂的计算,以便在所有情况下都能正常运行。