简体   繁体   中英

How do I call a function that prints a string variable which is defined in another function?

So here's my code up till now:

age = input("Enter Age: ")


def agePrint():
    print("You have entered " + age + ", which places you in " + ageGroup)

def ageFinder():
    if 00 <= int(age) <= 14:
        ageGroup = "Children"
        agePrint()
    elif 15 <= int(age) <= 24:
        ageGroup = "Youth"
        agePrint()

ageFinder()

So What I want is instead of writing the agePrint function manually for every age group, I just call a function, but the thing is the age group changes for every, well, agegroup. So I have to put it in the function as a variable, but when i call agePrint it says that ageGroup isn't defined. So how do I define the variable in such a way that it prints the suitable age group?

You can put age and ageGroup as parameters:


def agePrint(age, ageGroup):
    print("You have entered " + age + ", which places you in " + ageGroup)

def ageFinder():
    age = input("Enter Age: ")
    if 00 <= int(age) <= 14:
        ageGroup = "Children"
        agePrint(age, ageGroup)
    elif 15 <= int(age) <= 24:
        ageGroup = "Youth"
        agePrint(age, ageGroup)

ageFinder()

Pass the age group as a parameter to the function:

def agePrint(ageGroup):
    print("You have entered " + age + ", which places you in " + ageGroup)

    if 00 <= int(age) <= 14:
        agePrint("Children")
    elif 15 <= int(age) <= 24:
        agePrint("Youth")

You need to pass ageGroup parameter to agePrint() function.

def agePrint(ageGroup):
    print("You have entered " + age + ", which places you in " + ageGroup)

def ageFinder():
    if 00 <= int(age) <= 14:
        ageGroup = "Children"
    elif 15 <= int(age) <= 24:
        ageGroup = "Youth"
    agePrint(ageGroup)//Call the agePrint() function out of if block.
    
age = input("Enter Age: ")
ageFinder()

And also, there is no need to call agePrint() function seperately for if-elif block. You can assign a value to ageGroup and call function after that.

Just pass the variables as parameters to the functions:

age = input("Enter Age: ")


def agePrint(age,ageGroup):
    print("You have entered " + age + ", which places you in " + ageGroup)

def ageFinder(age):
    if 00 <= int(age) <= 14:
        ageGroup = "Children"
        agePrint(age,ageGroup)
    elif 15 <= int(age) <= 24:
        ageGroup = "Youth"
        agePrint(age,ageGroup)

ageFinder(age)

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