我正在编写一个简单的计算器程序,并且最初设置了价格变量。但是,当我输入一个函数时,它将清除我的变量数据,并说该变量是未定义的,即使它已经在程序的前面明确定义了。
n = int(input("How many tickets would you like?"))
cls()
if n >= 10:
print("Your group is large enough for our group discount!")
price = n * 5
else:
price = n * 6
def vet():
vet = input("Are you a veteran of any branch of the United States
Military?")
if vet.lower() in ['y', 'yes']:
print("Thank you for your service. Your discount has been applied.")
price *= 0.90
在此之前和之后当然还有更多的代码,但似乎输入此函数才使我的变量值清除。 我觉得好像缺少一个明显的答案,我们将不胜感激。
答案 0 :(得分:2)
为使我在上面的评论清楚,这是处理您遇到的问题的方法。它显式传递价格,然后返回价格,而不是依赖范围外的变量。
n = int(input("How many tickets would you like?"))
cls()
if n >= 10:
print("Your group is large enough for our group discount!")
price = n * 5
else:
price = n * 6
def ask_vet(price):
is_vet = input("Are you a veteran of any branch of the United States Military?")
if is_vet.lower() in ['y', 'yes']:
print("Thank you for your service. Your discount has been applied.")
price *= 0.90
return price
price = ask_vet(price)
答案 1 :(得分:-1)
如果将价格声明为全局变量,它将起作用。如果您有任何麻烦,请告诉我。
n = int(input("How many tickets would you like? "))
if n >= 10:
print("Your group is large enough for our group discount!")
price = n * 5
else:
price = n * 6
def vet():
global price
vet = input("Are you a veteran of any branch of the United States
Military? ")
if vet.lower() in ['y', 'yes']:
print("Thank you for your service. Your discount has been applied.")
price *= 0.90