I'm having a hard time figuring out how to pass a function's return as a parameter to another function. I've searched a lot of threads that are deviations of this problem but I can't think of a solution from them. My code isn't good yet, but I just need help on the line where the error is occurring to start with.
Instructions:
- create a function that asks the user to enter their birthday and returns a date object. Validate user input as well. This function must NOT take any parameters.
- create another function that takes the date object as a parameter. Calculate the age of the user using their birth year and the current year.
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
This is the Error I get:
TypeError: func2() missing 1 required positional argument: 'bday'
So far, I've tried:
- assigning the func1 to a variable and passing the variable as func2 parameter
- calling func1 inside func2
- defining func1 inside func2
CodePudding user response:
You're almost there, a few subtleties to consider:
- The
datetime
object must be assigned to a variable and returned. - Your code was not assigning the
datetime
object, but returning astr
object for input intofunc2
. Which would have thrown an attribute error as astr
has noyear
attribute. - Simply subtracting the years will not always give the age. What if the individual's date of birth has not yet come? In this case, 1 must be subtracted. (Notice the code update below).
For example:
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
Can be called using:
func2(bdate=func1())
CodePudding user response:
You can't use a function as a parameter, I think what you want to do is use it as an argument. You can do it like this:
import datetime as dt
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
func2(func1)
There are still some errors to be solved but the problem you had should be solved there