简体   繁体   中英

How to call a function within a function in python

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. Please help me out:)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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