Answer Error, Only outputting Zero

2024/11/18 7:32:34

I am coding in python and I cannot seem to figure out why when the amount of tickets sold is entered it does not calculate the full price of the tickets that were sold. Any help is appreciated, Thanks.

aLimit=300
bLimit=500
cLimit=100
aPrice=20
bPrice=15
cPrice=10
ticketSold=1
totalIncome=0def Main():getTickets(aLimit)sectionIncome=calcIncome(ticketSold,aPrice)sectionIncome+=totalIncomeprint("The theater generated this much money from section A "+str(sectionIncome))getTickets(bLimit)sectionIncome=calcIncome(ticketSold,bPrice)sectionIncome+=totalIncomeprint("The theater generated this much money from section B "+str(sectionIncome))getTickets(cLimit)sectionIncome=calcIncome(ticketSold,cPrice)sectionIncome+=totalIncomeprint("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 ticketSoldelse: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 Falsereturn Truedef calcIncome(ticketSold,price):return ticketSold*priceMain()
Answer

How to debug your (small) program

Okay so let's start from the top and go line-by-line. There's a lot of issues here.

aLimit=300
bLimit=500
cLimit=100
aPrice=20
bPrice=15
cPrice=10
ticketSold=1
totalIncome=0

These are all globals since you defined them in the module scope. That's a Bad Thing. Don't do it. If they're constants, use CAPS to mention that, but they should still not be global.

def Main(): # I mentioned in my comment, but Capitals are classes# by convention, use def main() insteadgetTickets(aLimit)

Let's stop and look at getTickets() so we can follow execution

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 CapitalizedticketSold=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

Okay so you invoked ticketsValid in there, so let's look there now...

def ticketsValid(Sold,limit): # another Capital here!while Sold > limit or Sold < 0: # this should be an if??print ("...")return Falsereturn 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 <=?

Alright, back to main--ahem--Main....

def Main():...sectionIncome = calcIncome(ticketSold,aPrice)

And hop back to calcIncome

def calcIncome(ticketSold,price):return ticketSold*price # why not just substitute this???

Main again

def Main():...sectionIncome += totalIncome# this sets sectionIncome equal to the current value of sectionIncome# plus the current value of totalIncome, which is currently zero.

Then basically the whole thing gets repeated down the function. There's your issue, the += adds zero to sectionIncome instead of adding sectionIncome to totalIncome!

The better way to do this!

Here's the problem. You're trying to use functional programming to do object-oriented tasks. Most of these kind of issues are when new programmers who are interested in video games think that the best task to learn programming is a text adventure. Unfortunately, the best languages for text adventures (those that easily implement a Finite State Machine) are not usually those that beginners start with, so it's hard to implement WELL!

In your case, you should be creating objects to do the workload for you. Python does this elegantly, but it's rarely in beginning tutorials. As an example, I wrote out a bit that does exactly what you did (defines three sections of seating in a theater and sells one ticket per section)

class Section(object):def __init__(self,price,limit):self.price = priceself.tickets_sold = 0self.limit = limit@propertydef sales(self):return self.price*self.tickets_solddef 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 userclass Theater(object):def __init__(self,sections):self.sections = sections@propertydef 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)

The big problem with this is just that you don't know how to do it. Creating an object that will stay constant, then throw several instances of it around with specific attributes is precisely the approach I would favor in this circumstance.

https://en.xdnf.cn/q/120100.html

Related Q&A

finding a pattern match and concatenating the rest of lines in python

I have a small data set to clean. I have opened the text file in Pycharm. The data set is like this:Code-6667+ Name of xyz company+ Address + Number+ Contact person+ Code-6668+ Name of abc company, A…

Flat a list of containing only one dict

I have a dict which contain a list product which will contain only one dict: d = {"thickness": 90.0,"mass_surf": 37.8,"res_therm": 0.75,"codename": "codenam…

How to breakup a list of list in a given way in Python [closed]

Its difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying thi…

Incrementing a counter while assigning it in python

Is it possible to do the following in python somehow?nodename = node%s % (++num if ct[0] != J else num)Or do I need to first do the increment and the assign it on the next line:if ct[0] != J:num += 1n…

Append two arrays together into one? (Numpy/Python)

I currently have an array of strings and Im trying to join it together with another array of strings to form a complete word to do some web parsing. For example:`Var1 [A B C, .... ....] Var2 …

Python 2.7 Isolate multiple JSON objects in a string

Ive to parse a text file that contains different kind of data. The most challenging is a line that contains three different JSON object (strings) and other data between them. Ive to divide the Json da…

pass different C functions with pointer arrays as the function argument to a class

I am trying to pass different functions which have pointers as arguments to a python function. One example of the input function as input parameter is the given normal function: Sample.pyxfrom cpython …

dynamic filter choice field in django

I am using django-filter to filter results on a page. I am able to use static choice filters like this:filters.pyFILTER_CHOICES = ( (, All States), (AL, Alabama), (AK, Alaska), (AZ, Arizona), #and so f…

How to print a table from a text file and fill empty spaces?

I have the following table in a txt file:|Client | Container weight | Country of Origin | Product code ||S4378 | 450 Ton | China | 457841 || | 350 Ton | Japan…

Open a file in python from 2 directory back

I want to read a file from 2 folders back.. with open(../../test.txt, r) as file:lines = file.readlines()file.close()I want to read from ../../ two folders back. but not work.. How i can do that ?