簡體   English   中英

如何調用 function 打印在另一個 function 中定義的字符串變量?

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

所以這是我到目前為止的代碼:

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()

所以我想要的不是為每個年齡組手動編寫 agePrint function,我只是調用 function,但問題是每個年齡組的年齡組都會發生變化。 所以我必須把它作為變量放在 function 中,但是當我調用agePrint 時,它說沒有定義ageGroup。 那么如何定義變量以打印合適的年齡組呢?

您可以將ageageGroup作為參數:


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()

將年齡組作為參數傳遞給 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")

您需要將 ageGroup 參數傳遞給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()

此外,對於 if-elif 塊,無需單獨調用 agePrint() function。 您可以為 ageGroup 分配一個值,然后調用 function 。

只需將變量作為參數傳遞給函數:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM