指示如何修复我的代码?此代码询问用户对已售票数的输入,并返回使用函数
生成的收入我不确定如何调用每个函数
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()
答案 0 :(得分:3)
回答您的第一个问题:调用所需的所有函数将函数名称放入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()
我希望这能回答你的问题。如果没有,请随时发表评论。如果是这样,请检查我的答案旁边的绿色复选标记。
答案 1 :(得分:1)
如果您只想知道如何使用嵌套函数:
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):......
我认为这将是一个更好的设计。