![](/img/trans.png)
[英]i have a string variable which comes with function names, how do I call the function in Python?
[英]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。 那么如何定義變量以打印合適的年齡組呢?
您可以將age
和ageGroup
作為參數:
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.