繁体   English   中英

传递函数的 output 作为另一个 function 的参数

[英]Passing a function's output as a parameter of another function

我很难弄清楚如何将函数的返回值作为参数传递给另一个 function。我搜索了很多与此问题有偏差的线程,但我想不出它们的解决方案。 我的代码还不好,但我只需要在错误发生的那一行开始的地方得到帮助。

指示:

  • 创建一个 function,要求用户输入他们的生日并返回日期 object。还要验证用户输入。 这个 function 不能带任何参数。
  • 创建另一个 function 以日期 object 作为参数。 使用他们的出生年份和当前年份计算用户的年龄。
def func1():
    bd = input("When is your birthday? ")
    try:
        dt.datetime.strptime(bd, "%m/%d/%Y")
    except ValueError as e:
        print("There is a ValueError. Please format as MM/DD/YYY")
    except Exception as e:
        print(e)
    return bd

def func2(bd):
    today = dt.datetime.today()
    age = today.year - bd.year
    return age

这是我得到的错误:

TypeError: func2() missing 1 required positional argument: 'bday'

到目前为止,我已经尝试过:

  • 将 func1 分配给变量并将该变量作为 func2 参数传递
  • 在 func2 中调用 func1
  • 在 func2 中定义 func1

你快到了,需要考虑一些微妙之处:

  1. datetime时间 object 必须分配给一个变量并返回
  2. 您的代码没有分配datetime时间 object,而是返回一个str object 以输入到func2中。 这会引发属性错误,因为str没有year属性。
  3. 简单地减去年份并不总能得出年龄。 如果个人的出生日期尚未到来怎么办? 在这种情况下,必须减去 1。 (注意下面的代码更新)。

例如:

from datetime import datetime as dt

def func1():
    bday = input("When is your birthday? Enter as MM/DD/YYYY: ")
    try:
        # Assign the datetime object.
        dte = dt.strptime(bday, "%m/%d/%Y")
    except ValueError as e:
        print("There is a ValueError. Please format as MM/DD/YYYY")
    except Exception as e:
        print(e)
    return dte  # <-- Return the datetime, not a string.

def func2(bdate):
    today = dt.today()
    # Account for the date of birth not yet arriving.
    age = today.year - bdate.year - ((today.month, today.day) < (bdate.month, bdate.day))
    return age

可以调用使用:

func2(bdate=func1())

我认为您想做的是将其用作参数。 你可以这样做:

import datetime as dt

def func1():
    bd = input("When is your birthday? ")
    try:
        date_object = dt.datetime.strptime(bd, "%m/%d/%Y")
    except ValueError as e:
        print("There is a ValueError. Please format as MM/DD/YYY")
    except Exception as e:
        print(e)
    return date_object

def func2(bd)
    today = dt.datetime.today()
    age = today.year - bd.year
    return age

func2(func1())

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM