如何调用嵌套函数?
有没有人能给我一些建议,帮我修复我的代码?这段代码是用来询问用户售出多少张票,然后计算出产生的收入,使用了函数。
我不太确定该怎么调用每个函数。
secA = 20
secB = 15
secC = 10
def main():
print("The income generated from all sections is: ", total)
def getTickets(A,B,C):
sectionA = int(input("Please enter the number of tickets sold in section A: ")
sectionB = int(input("Please enter the number of tickets sold in section B: ")
sectionC = int(input("Please enter the number of tickets sold in section C: ")
def ticketsValid():
while sectionA > 300:
print("ERROR: Section A has a limit of 300 seats")
while sectionB > 500:
print("ERROR: Section B has a limit of 500 seats")
while sectionC > 200:
print("ERROR: Section C has a limit of 200 seats")
def calcIncome():
total = secA * sectionA + secB * sectionB + secC * sectionC
print("The income generated is $", format(total, '.2f'))
main()
2 个回答
如果你只是想知道怎么使用嵌套函数:
def f():
def g(): #this defines a function but does not call it
print "run g"
g() # this calls g.
通常情况下,嵌套函数不应该在它的父函数外部被使用。因为使用嵌套函数的目的就是让这个函数只帮助它的父函数完成一些事情。如果你想在外部使用它,考虑把它定义成一个新的函数。
在你的情况下,你需要考虑怎么把代码拆分成几个部分。
如果我是你,我会用 getTickets() 来获取票务信息。
ticketsValid 这个函数可以用,但我会让它返回一个布尔值(真或假)。
calcIncome 函数则应该返回总收入。
所以大致的设计可以是这样的:
def main():
(A, B, C) = getTickets()
if(ticketsValid(A, B, C)):
income = calcIncome(A, B, C)
print("The income generated from all sections is: ", income)
def getTickets():......
def ticketsValid(A, B, C):......
def calcIncome(A, B, C):......
我觉得这样设计会更好。
首先,回答你的第一个问题:要调用所有的函数,你需要把函数的名字放进 main()
函数里。不过,你的代码还有其他几个错误,所以我决定一步一步带你走过这个程序。
首先,我们设置价格:
secA = 20
secB = 15
secC = 10
这是第一个函数,叫做 getTickets()
def getTickets():
global A
A = int(input("Please enter the number of tickets sold in section A: "))
global B
B =int(input("Please enter the number of tickets sold in section B: "))
global C
C =int(input("Please enter the number of tickets sold in section C: "))
注意在我使用变量之前有个 global
这个词。这是告诉计算机,这个变量可以在任何地方使用。接下来,注意到有两个括号 - 因为 int()
和 input()
都是函数,所以我们需要这样来表示。
我修正了你的 ticketsValid()
函数的代码。通常,把函数放在另一个函数里面不是个好主意,所以这个函数和上面的代码在同一缩进级别。
def ticketsValid(A,B,C):
while A > 300 or A < 0:
print("ERROR: Section A has a limit of 300 seats\n")
A = int(input("Please enter the number of tickets sold in section A: "))
while B > 500 or B < 0:
print("ERROR: Section B has a limit of 500 seats")
B =int(input("Please enter the number of tickets sold in section B: "))
while C > 200 or C < 0:
print("ERROR: Section C has a limit of 200 seats")
C =int(input("Please enter the number of tickets sold in section C: "))
这个函数获取上面的变量,并检查它们是否有效。注意我添加了一个检查负数的条件 - 你不能卖负数的票。
然后我们来看 calcIncome(A,B,C)
:
def calcIncome(A, B, C):
total = A * secA + B * secB + C * secC
print ("The income generated is $%d" % (total))
首先,我们把各个部分的数量乘以设定的价格来计算总收入。然后,我们把结果打印出来。
最后,我们需要调用这些函数。我用了你想法中的 main() 函数,它会使用其他函数。它看起来是这样的。
def main():
getTickets()
ticketsValid(A,B,C)
calcIncome(A, B, C)
它在运行时会按正确的顺序简单地调用其他函数。
最后,我们通过输入以下内容来调用 main()
函数:
main()
希望这能回答你的问题。如果没有,欢迎留言。如果有,请检查我答案旁边的绿色勾勾。