[英]Passing a function's output as a parameter of another function
我很难弄清楚如何将函数的返回值作为参数传递给另一个 function。我搜索了很多与此问题有偏差的线程,但我想不出它们的解决方案。 我的代码还不好,但我只需要在错误发生的那一行开始的地方得到帮助。
指示:
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'
到目前为止,我已经尝试过:
你快到了,需要考虑一些微妙之处:
datetime
时间 object 必须分配给一个变量并返回。datetime
时间 object,而是返回一个str
object 以输入到func2
中。 这会引发属性错误,因为str
没有year
属性。例如:
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.