This is a discount function in python that applies a discount to a specified price. You get a 10% discount if you are a member, and you get a 5% discount if the item is on sale.
def calculate_price(orig_price, is_member="Yes", is_on_sale="Yes"):
member_discount = 0.10
sale_discount = 0.05
if is_member == True:
if is_on_sale == True:
price = orig_price - (orig_price * (member_discount sale_discount))
else:
price = orig_price - (orig_price * member_discount)
elif is_member == False:
if is_on_sale == True:
price = orig_price - (orig_price * sale_discount)
else:
price = orig_price
return price
orig_price = float(input("Enter price: "))
is_member = input("Member? (yes or no): ")
is_on_sale = input("sale? (yes or no): ")
print(calculate_price(orig_price, is_member="yes", is_on_sale="yes"))
My problem is when I try to run it I get the error:
File "", line 23, in File "", line 17, in calculate_price UnboundLocalError: local variable 'price' referenced before assignment
Anyone know why this is and how to fix it?
CodePudding user response:
You pass "is_member" as a string "yes", yet your code assumes it is a boolean of True or False, consequently none of your code paths setting variable "price" executes. Unify your code to either pass booleans as is_member, or change the logic inside the function that compares "is_member" to a boolean to compare to a string of interest instead.
CodePudding user response:
If you call a function like this, the arguments the function gets, is_member and is_on_sale, would always be "yes"!
print(calculate_price(orig_price, is_member="yes", is_on_sale="yes"))
Perhaps you would like to try this:
print(calculate_price(orig_price, is_member, is_on_sale))