Hollstream
Hollstream

Reputation: 9

How to call another function within a function?

How do I avoid having a long list with function calls in the end of the program like down below? Below is just an example but when I code larger programs it can easily become a "list" of over 20 function calls.

def ask_age():
    age = input("age: ")
    return age

def calculate_age_minus_ten(age):
    age_minus_ten = int(age) - 10
    return age_minus_ten

def print_phrase(age,age_minus_ten):
    print("I am " + str(age) + " years old. 10 years ago I was " + str(age_minus_ten) + " 
    years old")

age = ask_age()
age_minus_ten = calculate_age_minus_ten(age)
print_phrase(age, age_minus_ten)

I would like to make it look something like this:

def ask_age():
    age = input("age: ")
    return age

def calculate_age_minus_ten():
    age_minus_ten = int(ask_age()) - 10
    return age_minus_ten

def print_phrase():
    print("I am " + ask_age() + " years old. 10 years ago I was " + str(calculate_age_minus_ten()) + " years old")

print_phrase()

It has worked to code according to example 1 in school for a couple of weeks now, but when I have to do larger programs, it becomes difficult to collect all function calls at the bottom. So what I want to do is to continuously call functions in the code so that I only need to call one function at the bottom.

Upvotes: 0

Views: 113

Answers (1)

Pedro Maia
Pedro Maia

Reputation: 2732

My suggestion: don't use multiple functions, do everything you need in a single one and if you still want those values you can return them:

def foo():
    age = int(input("age: "))
    age_minus_ten = age - 10
    print(f"I am {age} years old. 10 years ago I was {age_minus_ten}"
    return age, age_minus_ten

age, age_minus_ten = foo() # If you want the return values

Upvotes: 1

Related Questions