定义一个函数,该函数接受两个参数,包括名称(字符串)和出生日期(日期)



我的作业要求我: 定义一个函数make_birthday_intro(),它接受两个参数:名称(字符串)和出生日期(日期)。

您应该使用第 1 部分中的make_introduction()功能!您可能需要计算一个变量以传递到该函数调用中。

提示:使用relativedelta()函数计算该人的当前年龄,以及他们何时长大 1 岁。您可以通过访问 .days 或 .years 属性(例如 time_difference.年)从relativedelta值(例如 time_difference)中获取天数或年数。

第二部分

通过调用您的make_birthday_intro()函数并传入您的名称(已经是一个变量!)和您的出生日期来创建变量my_bday_intro。创建变量后打印变量。

我的导师和我真的很努力地一起解决这个问题,但我相信部分问题在于我们没有一起完成作业的第一部分,所以他没有完全理解作业的这一部分,我后来意识到这可能是我们陷入困境的部分原因,我们错过了一个变量。 我不知道从作业的第二部分开始,因为我们被困在make_birthday_intro部分。

我的第 1 部分中的make_introduction代码,包括导致它的所有代码

my_name = "Kaitlyn Griffith"
print(my_name)
my_age = 24
print(my_age)
def make_introduction(my_name, my_age):
return "Hello, my name is, " + my_name + " and I'm " + str(my_age) + " years old."

我对家庭作业问题的尝试

import datetime
def make_birth_intro(name, date_of_birth):
age = datetime.date.today() - date_of_birth
print(age)
dateThing = datetime.date(1995, 2, 10)
make_birth_intro(make_introduction, dateThing)

我不确定从作业的第二部分开始

此函数应返回格式为"你好,我的名字是 {NAME} 和我是 {AGE} 岁。在 {N} 天里,我将是 {NEW_AGE}"(将 {NAME}、{AGE}、{N} 和 {NEW_AGE} 替换为适当的值)。

它应该在哪里准备好 "你好,我叫凯特琳,今年 24 岁。再过274天,我就25岁了">

但是,我目前的输出是:

8857 days, 0:00:00

老实说,我不确定我应该在第二部分中寻找什么

你离得很近。要以年为单位获取年龄,您可以仅从日期中获取年份参数并减去它们以获得年差。 要获取生日的剩余天数,您可以先获取当前年份的出生日期,然后从当前日期中减去该日期以获得天数差。当生日已经过去了,但可以通过简单的年数增量来改变时,就会出现并发症。

你会大致这样做(没有测试过自己):

def make_birth_intro(name, date_of_birth):
today = datetime.date.today()
age = today.year - date_of_birth.year
print(age)
this_birthday = date_of_birth.replace(year = today.year)
if(this_birthday < today):
this_birthday = this_birthday.replace(year=this_birthday.year + 1)
days_left = this_birthday - today
print(days_left.days)

我没有读太多关于整个问题陈述的内容,正如 razdi 说你很接近时,我重写了一些东西。

使用此解决方案,您只需要DOB而不是您的年龄。


import datetime
def make_introduction(my_name, birth_info):
"""
Handles the printing
"""
return f"Hello, my name is {my_name} and I'm {birth_info[0]} years old, in {birth_info[1]} I'll be {birth_info[0] + 1}."
def make_birth_intro(date_of_birth):
# // is a floor division to get age in years given days
today = datetime.date.today()
age = (today - date_of_birth).days // 365
next_birthday = datetime.date(today.year, date_of_birth.month, date_of_birth.day)
if next_birthday < today:
"""
If we already had a birthday this year then add a year.
"""
next_birthday = next_birthday.replace(year=today.year + 1) 
days_till_level_up = (next_birthday - today).days
return age, days_till_level_up
my_name = "Kaitlyn Griffith"
DOB = datetime.date(1995, 2, 10)
output = make_introduction(my_name, make_birth_intro(DOB))
print(output)

输出:

Hello, my name is Kaitlyn Griffith and I'm 24 years old, in 274 I'll be 25.

最新更新