经过100次尝试,我终于使它工作了,但是我想知道是否还有另一种编写此代码的方法,我是python的新秀,我将不胜感激。
import datetime
date= datetime.datetime.now()
def age_calc(age):
age = date.year - int(dob)
return age
dob=input("Please Enter DOB here: ")
print("You are %s years old" % age_calc(dob))
答案 0 :(得分:0)
即使对于像这样的小型程序,也总会有一些东西需要改进和学习。一些建议:
age_calc
的参数,但这实际上是date_of_birth。每个人都知道dob
是什么,尽管最好将其拼写出来,尤其是在没有上下文的情况下。if __name__ == '__main__':
构造并将程序拆分为可完成一项功能的多个函数。f"Hello {name}"
请看一下下面的重构代码。
import datetime
def age_calc(date_of_birth):
current_date = datetime.datetime.now()
age_days = current_date - date_of_birth
age_years = int(age_days.days / 365.25)
return age_years
def get_date_of_birth():
answered = False
while not answered:
dob_answer = input("Please Enter DOB here (DD-MM-YYYY) (enter q to quit): ")
if dob_answer in ['q', 'Q']:
exit()
try:
date_of_birth = datetime.datetime.strptime(dob_answer, "%d-%m-%Y")
answered = True
except ValueError:
print(f"{dob_answer} has incorrect format, use: d-m-yyyy")
return date_of_birth
def print_age(date_of_birth):
print(f"You are {age_calc(date_of_birth)} years old")
if __name__ == '__main__':
while True:
dob = get_date_of_birth()
print_age(dob)
祝你好运!