KissMyAxe
KissMyAxe

Reputation: 45

Local variable referenced before assignment. Can you assign global var in a function?

I'm getting the error: local variable 'import_tax' referenced before assignment. I had it working 5 minutes ago but can't figure out what I did to break it or how to fix it. Trying to get the code to calculate tax depending on if certain criteria are met ie. exempt or imported, etc.

I think I'm getting confused with the assignment of global variables. Like if I should assign import_tax and sales_tax = 0 before the function or something like that? But that returns all tax = 0 even if it should be added to the tax. Here's my code:

exempt_items = ['book', 'food', 'chocolate', 'medicine' ]

item_dict = {}

def main():
    add_item = input("Add item? Y/N: ")
    while add_item.capitalize() == 'Y':
        quantity = input("How many? ")
        item_to_add = input("Item: ")
        original_price = float(input("Price: "))
        imported = False
        exempt = False
        if 'import' in item_to_add:
            imported = True
        for i in range(0, len(item_to_add.split())):        # search string see if exempt or not
            item_to_add = item_to_add.rstrip('s')           # remove plurals
            if item_to_add.split()[i] in exempt_items:
                exempt = True
        if imported == True:
            import_tax = original_price*0.05                # add 5% on imported goods   
        print("Imported", imported)       
        if exempt == False:
            sales_tax = original_price*0.1                  # add 10% if not exempt  add to total sales tax 
        print("Exempt", exempt)
        print("IT:",import_tax, "ST", sales_tax)
        total_tax = sales_tax + import_tax
        final_price = round((original_price + total_tax) * float(quantity), 2) 
        item_to_add = quantity + ' ' + item_to_add
        item = {item_to_add: final_price}
        item_dict.update(item)
        print("Final Price", final_price)
        add_item = input("Add item? Y/N ")
    print('-------------------')
    for key, val in item_dict.items():
        print (key, ':', val)
    print('-------------------')
    print("Sales Taxes:",round(total_tax, 2))
    print("Total:",round(sum(item_dict.values()) , 2))
    print('-------------------')


if __name__ == '__main__':
    main()

So input such as "imported chocolates" at 10, should return:
1 imported chocolates: 10.50
Sales tax: 0.50
Total: 10.50

Upvotes: 0

Views: 586

Answers (1)

Jmonsky
Jmonsky

Reputation: 1519

You should declare import_tax and sales_tax as 0 before the if statements where you set them. This is because if imported is False then you wont assign a value to it and you get a reference error.

Upvotes: 1

Related Questions