NameError:全局名称未定义

1 投票
2 回答
2678 浏览
提问于 2025-04-17 21:49

我的Python代码总是出现“名称错误”,说全局变量ticketSold没有定义。我不太确定该怎么解决,因为我确实把它定义成了全局变量。希望能得到一些帮助。

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

2 个回答

1

这里有一个版本,它:

  • 兼容Python 2和Python 3
  • 不使用任何全局变量
  • 可以轻松扩展到任意数量的部分
  • 展示了面向对象编程的一些好处(与使用很多命名变量,比如 aLimitbLimit 等相比:当你需要处理27个部分时,你会怎么做?)

所以:

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()

这给我们带来了

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.
4

global varname 并不会神奇地为你创建一个 varname。你必须在全局命名空间中声明 ticketSold,比如在 cPrice=10 之后。global 只是确保当你提到 ticketSold 时,你是在使用名为 ticketSold 的全局变量,而不是一个同名的局部变量。

撰写回答