I'm very new to Python (~8 hours of experience and study in a span of two days) and doing some self-created exercises to practice newly learned information. Currently focusing in classes and functions. The code is regarding selling fruits: there is a class fruit, which takes name, color, price_usd and its objects. There is also a "shopping cart" list and total_cost (initially set as 0). I have made the code work properly, however now trying to not repeat code using functions.
I created a function called "buy", which prints which fruit was chosen, adds it to the shopping cart and add its value to total_cost. However, I am getting "Unresolved reference" for total_cost (but not for shopping cart, which is also a variable outside the function?)
Error message: "UnboundLocalError: local variable 'total_cost' referenced before assignment)
(Code shown is a separate file with the problem I am trying to solve to, then, include in the main file. No new variables, though, as main file only had a lot of conditional statements and new objects.)
Tried creating total_cost before and after function. Also tried to 'manually' add fruit_choice.price_usd to total_cost: "total_cost = total_cost + fruit_choice.price_usd" It created local variable "total_cost" and gave out "Unresolved reference" for second total_cost
import fruit as fr
apple = fr.Fruits("Apple", "red", price_usd=0.88)
shopping_cart = []
# total_cost = 0
def buy(fruit_choice):
print(f"A(n) {fruit_choice.name} has been added to your shopping cart.")
shopping_cart.append(fruit_choice.name)
##############################################
total_cost += fruit_choice.price_usd
print(f" The total cost is: {total_cost}")
##############################################
total_cost = 0
print(shopping_cart, "\n", buy(apple))
(Between the ###... is where the error message is coming from.)
I expected the fruit_choice.price_usd being added to total_cost. It would be easier if that was the case, as it is the same code for every fruit.
Thank you in advance for your precious help!