简体   繁体   English

NameError:全局名称未定义

[英]NameError: Global Name not defined

my python code keeps getting nameerror, global variable not defined on ticketSold. 我的python代码不断收到nameerror,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 def calcIncome(ticketSold,price):退回ticketSold * price

Saying global varname does not magically create varname for you. global varname并不能为您神奇地创建varname You have to declare ticketSold in the global namespace, for example after cPrice=10 . 您必须在全局名称空间中声明ticketSold ,例如在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. global仅确保当您说ticketSold ,您使用的是名为ticketSold的全局变量,而不是同名的局部变量。

Here is a version which: 这是一个版本:

  • is Python 2 / 3 compatible 与Python 2/3兼容
  • 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?) 演示了OOP的一些好处(与命名变量的泛滥相反: aLimitbLimit等-达到27个部分时做什么?)

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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM