gpt4 book ai didi

python - 全局名称未定义错误

转载 作者:太空宇宙 更新时间:2023-11-04 10:39:03 25 4
gpt4 key购买 nike

我的折扣变量总是出错。名称错误:未定义全局名称“折扣”。请看看我的代码并帮助我。我根本不想修改函数的参数。

def finddiscount(quantity):
if quantity >= 1 and quantity <= 9:
discount = 0
elif quantity >= 10 and quantity <= 19:
discount = .2
elif quantity >= 20 and quantity <= 49:
discount = .30
elif quantity >= 50 and quantity <= 99:
discount = .40
elif quantity >= 100:
discount = .50
return discount
def calctotal(quantity, price):
finddiscount(quantity)
disc = (price*quantity)*discount
total = (price*quantity)
due = (price*quantity)-(price*quantity)*dicount
print ("\t","Order total $",format(total, "10.2"),"\n\t","Discount $",format(disc,"10.2"),"\n\t","Amount Due $",format (due, "10.2"),sep="")
def main():
quantity = int(input("How many packages where purchased?"))
price = float(input("How much is each item?"))
calctotal(quantity, price)
main()

最佳答案

如果您想在多 block 范围内访问它,您必须将 discount 声明为全局变量。

discount = 0

def finddiscount(quantity):
...
global discount # Needed to modify global copy of discount
discount = 1

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

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