gpt4 book ai didi

python - NameError:未定义全局名称

转载 作者:行者123 更新时间:2023-12-02 04:34:11 27 4
gpt4 key购买 nike

我的 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

最佳答案

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

关于python - NameError:未定义全局名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22332901/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com