![](/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.