关于如何修复我的代码的指针?此代码要求用户输入售出的门票数量,并返回使用函数生成的收入
我不确定如何调用每个函数
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()发布于 2013-03-11 05:37:01
回答您的第一个问题:要调用所有函数,您需要将函数的名称放入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()我希望这回答了你的问题。如果没有,请随时发表评论。如果是,请勾选我的答案旁边的绿色复选标记。
发布于 2013-03-11 05:57:12
如果您只想知道如何使用嵌套函数:
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):......我认为这会是一个更好的设计。
https://stackoverflow.com/questions/15327457
复制相似问题