Home > Mobile >  How can I have one function calling another function (as its argument)?
How can I have one function calling another function (as its argument)?

Time:07-08

def GetAge():
   age = int(input("Please enter your age: "))
   return age
  
    
def DetermineAge():
    if age < 2:
        print("Stage of Life: A Baby")
    elif age < 4:
        print("Stage of Life: A Toddler")
    elif age < 13:
        print("Stage of Life: A Kid")
    elif age < 20:
        print("Stage of Life: A Teenager")
    elif age < 65:
        print("Stage of Life: An Adult")
    elif age >= 65:
        print("Stage of Life: An Elder")
    else:
        print("Mistakes were made, please restart the program and try again.")

age = GetAge()
DetermineAge() 

Trying to remove age out of age = GetAge how do I do that with my function? I already define age in my function and return it I only want my main code to say GetAge() and DetermineAge()

CodePudding user response:

Change DetermineAge to take age as an argument:

def DetermineAge(age):
    # rest of function is the same

and then the caller can pass the value as an argument directly instead of needing the variable age to be defined in the caller's own scope:

DetermineAge(GetAge())

Alternatively, you could have DetermineAge call GetAge() itself:

def DetermineAge():
    age = GetAge()
    # rest of function is the same

and then the caller can just do:

DetermineAge()

If you wanted the function itself to be an argument, you could also do that:

def DetermineAge(get_age_func):
    age = get_age_func()
    # rest of function is the same
DetermineAge(GetAge)

CodePudding user response:

You can use a decorator function that takes a function as an argument and calls it with @, like this

def DetermineAge(func):
    def wrapper(*args, **kwargs):
        age = func(*args, **kwargs)
        if age < 2:
            print("Stage of Life: A Baby")
        elif age < 4:
            print("Stage of Life: A Toddler")
        elif age < 13:
            print("Stage of Life: A Kid")
        elif age < 20:
            print("Stage of Life: A Teenager")
        elif age < 65:
            print("Stage of Life: An Adult")
        elif age >= 65:
            print("Stage of Life: An Elder")
        else:
            print("Mistakes were made, please restart the program and try again.")
        return age
    return wrapper


@DetermineAge
def GetAge():
    age = int(input("Please enter your age: "))
    return age


age = GetAge()
  • Related