我在python编码,我似乎无法弄清楚为什么当输入售票数量时,它不会计算售出的门票的全价。感谢任何帮助,谢谢。
aLimit=300
bLimit=500
cLimit=100
aPrice=20
bPrice=15
cPrice=10
ticketSold=1
totalIncome=0
def Main():
getTickets(aLimit)
sectionIncome=calcIncome(ticketSold,aPrice)
sectionIncome+=totalIncome
print("The theater generated this much money from section A "+
str(sectionIncome))
getTickets(bLimit)
sectionIncome=calcIncome(ticketSold,bPrice)
sectionIncome+=totalIncome
print("The theater generated this much money from section B "+
str(sectionIncome))
getTickets(cLimit)
sectionIncome=calcIncome(ticketSold,cPrice)
sectionIncome+=totalIncome
print("The theater generated this much money from section C "+
str(sectionIncome))
print("The Theater generated "+str(totalIncome)+" total in ticket sales.")
def getTickets(limit):
ticketSold=int(input("How many tickets were sold? "))
if (ticketsValid(ticketSold,limit)==True):
return ticketSold
else:
getTickets(limit)
def ticketsValid(Sold,limit):
while (Sold>limit or Sold<0):
print("ERROR: There must be tickets less than "+
str(limit)+" and more than 0")
return False
return True
def calcIncome(ticketSold,price):
return ticketSold*price
Main()
答案 0 :(得分:0)
阅读+=
运算符。 totalIncome只设置为0.
答案 1 :(得分:0)
您需要将sectionIncome+=totalIncome
替换为totalIncome+=sectionIncome
代码
aLimit=300
bLimit=500
cLimit=100
aPrice=20
bPrice=15
cPrice=10
ticketSold=1
totalIncome=0
def Main():
getTickets(aLimit)
sectionIncome=calcIncome(ticketSold,aPrice)
totalIncome=sectionIncome
print("The theater generated this much money from section A "+str(sectionIncome))
getTickets(bLimit)
sectionIncome=calcIncome(ticketSold,bPrice)
totalIncome+=sectionIncome
print("The theater generated this much money from section B "+str(sectionIncome))
getTickets(cLimit)
sectionIncome=calcIncome(ticketSold,cPrice)
totalIncome+=sectionIncome
print("The theater generated this much money from section C "+str(sectionIncome))
print("The Theater generated "+str(totalIncome)+" total in ticket sales.")
def getTickets(limit):
ticketSold=int(input("How many tickets were sold? "))
if (ticketsValid(ticketSold,limit)==True):
return ticketSold
else:
getTickets(limit)
def ticketsValid(Sold,limit):
while (Sold>limit or Sold<0):
print ("ERROR: There must be tickets less than "+str(limit)+" and more than 0")
return False
return True
def calcIncome(ticketSold,price):
return ticketSold*price
Main()
答案 2 :(得分:0)
好的,让我们从顶部开始逐行。这里有很多问题。
aLimit=300
bLimit=500
cLimit=100
aPrice=20
bPrice=15
cPrice=10
ticketSold=1
totalIncome=0
这些都是全局变量,因为您在模块范围中定义了它们。那是一件坏事。不要这样做。如果它们是常量,请使用CAPS
来提及,但它们仍然不是全局的。
def Main(): # I mentioned in my comment, but Capitals are classes
# by convention, use def main() instead
getTickets(aLimit)
让我们停下来看看getTickets()
,以便我们跟进执行
def getTickets(limit): # camelCase is not advised per PEP8, but it's still around
# so I wouldn't worry about this one so much as Capitalized
ticketSold=int(input("How many tickets were sold? "))
# perfect implementation, though be prepared for users who
# will type forty instead of 40!
if (ticketsValid(ticketSold,limit)==True):
return ticketSold
# so any time you write `if ___ == True`, stop and realize that the compare
# is unnecessary. if ticketsValid(ticketSold,limit) works just as well!
else:
getTickets(limit)
# wha-? If the tickets aren't valid, we're RECURSING??! This is an infinite loop.
# are you doing this to prompt for more input if tickets aren't valid? That's Bad
好的,所以你在那里调用ticketsValid
,所以让我们现在看看......
def ticketsValid(Sold,limit): # another Capital here!
while Sold > limit or Sold < 0: # this should be an if??
print ("...")
return False
return True
# Since you have a set amount, this is MUCH easier written as:
## def ticketsValid(sold,limit):
## return 0 < sold < limit
# but should this be <=?
好的,回到main
- 哼 - Main
....
def Main():
...
sectionIncome = calcIncome(ticketSold,aPrice)
然后跳回calcIncome
def calcIncome(ticketSold,price):
return ticketSold*price # why not just substitute this???
再次 Main
def Main():
...
sectionIncome += totalIncome
# this sets sectionIncome equal to the current value of sectionIncome
# plus the current value of totalIncome, which is currently zero.
然后基本上整个事情都重复了这个功能。如果您有问题,+=
会向sectionIncome
添加零,而不是将sectionIncome
添加到totalIncome
!
这就是问题所在。您正在尝试使用函数式编程来执行面向对象的任务。大多数这类问题都是对视频游戏感兴趣的新程序员认为学习编程的最佳任务是文本冒险。不幸的是,文本冒险的最佳语言(那些容易实现有限状态机的语言)通常不是那些初学者开始的语言,因此很难实现WELL!
在您的情况下,您应该创建对象来为您完成工作量。 Python优雅地做到了这一点,但在开始教程时很少。作为一个例子,我写了一些与你所做的完全相同的事情(在剧院中定义了三个座位并且每个部分卖出一张票)
class Section(object):
def __init__(self,price,limit):
self.price = price
self.tickets_sold = 0
self.limit = limit
@property
def sales(self):
return self.price*self.tickets_sold
def sell(self,qty=1):
if not isinstance(qty,int): raise TypeError("Must sell an int of tickets")
if qty < 1: raise ValueError("Must sell positive tickets")
qty = min(qty,self.limit-self.tickets_sold)
self.tickets_sold += qty
# optional print statement for the user
class Theater(object):
def __init__(self,sections):
self.sections = sections
@property
def sales(self):
return sum(section.sales for section in self.sections)
theater = Theater([Section(20,300),
Section(15,500),
Section(10,100)])
for section in theater.sections:
section.sell(1)
print(theater.sales)
这个问题的关键在于你不知道该怎么做。创建一个保持不变的对象,然后使用特定属性抛出它的几个实例正是我在这种情况下所青睐的方法。
答案 3 :(得分:0)
sectionIncome+=totalIncome
这是错误的方法。要将totalIncome
的值添加到sectionIncome
,语法为
totalIncome+=sectionIncome
您还需要将global totalIncome
添加到Main
的开头 - 或者更好的是,完全取消全局变量,就像之前经常被告知的一样。
最后,您的getTickets
函数返回一个计算值,但调用它的代码不会将该结果存储在任何位置。相反,您只需在全局初始化中设置ticketSold=1
,然后将其用作乘数,而不是用户输入的实际票数。
作为一般观察,你有很多重复的代码,而你所拥有的函数并不是很有用(它们不包含复杂的行为,也没有重复的功能)。如果您是初学者,请专注于简单的流程,然后将复杂的重复操作分解为循环或函数。也许是这样的:
def income ():
total = 0
for ticket_type, limit, price in [('A', 300, 20),
('B', 500, 15),
('C', 100, 10)]:
print "How many %s tickets sold? (Max %d):" % (ticket_type, limit),
sold = -1
while sold < 0 or sold > limit:
if sold != -1:
print "Sorry. Try again:",
sold = raw_input()
try:
sold = int(sold)
except:
pass
total += sold*price
print "total %d" % total
income()
请注意用户友好的手势,指示输入提示中每个类别允许的最大值( - :
循环驱动程序有点疣;一种更为流畅的方法是声明一个类TicketCategory
,并有三个实例A
,B
和C
,并提供报告其名称,价格和方法的方法可用金额,但这是为了以后。