NameError: Global Name not defined

my python code keeps getting nameerror, global variable not defined on ticketSold. I am not sure how to fix this, as I did define it as a global variable. Any help is appreciated.

aLimit=300
bLimit=500
cLimit=100
aPrice=20
bPrice=15
cPrice=10

def Main():
global ticketSold

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(ticketSold,limit):

while (ticketSold>limit or ticketSold<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

Answers


Saying global varname does not magically create varname for you. You have to declare ticketSold in the global namespace, for example after cPrice=10. global only makes sure that when you say ticketSold, you're using the global variable named ticketSold and not a local variable by that same name.


Here is a version which:

  • is Python 2 / 3 compatible
  • does not use any global variables
  • is easily extended to any number of sections
  • demonstrates some benefits of OOP (as opposed to a proliferation of named variables: aLimit, bLimit, etc - what will you do when you reach 27 sections?)

And so:

import sys

if sys.hexversion < 0x3000000:
    # Python 2.x
    inp = raw_input
else:
    # Python 3.x
    inp = input

def get_int(prompt):
    while True:
        try:
            return int(inp(prompt))
        except ValueError:  # could not convert to int
            pass

class Section:
    def __init__(self, name, seats, price, sold):
        self.name  = name
        self.seats = seats
        self.price = price
        self.sold  = sold

    def empty_seats(self):
        return self.seats - self.sold

    def gross_income(self):
        return self.sold * self.price

    def sell(self, seats):
        if 0 <= seats <= self.empty_seats():
            self.sold += seats
        else:
            raise ValueError("Cannot sell {} seats, only {} are available".format(seats, self.empty_seats))

def main():
    # create the available sections
    sections = [
        Section("Loge",  300, 20., 0),
        Section("Floor", 500, 15., 0),
        Section("Wings", 100, 10., 0)
    ]

    # get section seat sales
    for section in sections:
        prompt = "\nHow many seats were sold in the {} Section? ".format(section.name)
        while True:
            # prompt repeatedly until a valid number of seats is sold
            try:
                section.sell(get_int(prompt))
                break
            except ValueError as v:
                print(v)
        # report section earnings
        print("The theatre earned ${:0.2f} from the {} Section".format(section.gross_income(), section.name))

    # report total earnings
    total_earnings = sum(section.gross_income() for section in sections)
    print("\nTotal income was ${:0.2f} on ticket sales.".format(total_earnings))

if __name__=="__main__":
    main()

which gives us

How many seats were sold in the Loge Section? 300
The theatre earned $6000.00 from the Loge Section

How many seats were sold in the Floor Section? 300
The theatre earned $4500.00 from the Floor Section

How many seats were sold in the Wings Section? 100
The theatre earned $1000.00 from the Wings Section

Total income was $11500.00 on ticket sales.

Need Your Help

how to uplaod multiple images from i pad gallery using ionic and cordova plugin?

angularjs image cordova ionic cordova-plugins

I want to upload multiple images in iPad using ionic and cordovaImagePicker plugin.

Execute a stored procedure in another database with params

sql-server tsql stored-procedures dynamic-sql

I need to get the column names of a table that's located in another database. The following script works for the active database but I need to run it against another database in the same server ins...