1
votes

I am a newbie in python programming practising and made my first basic program

I have to access and print the variable that is local within if function and if I am trying to access it, it shows local variable might be referenced

here is the full code

def main():
print("Please place your order by filling the options")

name = input("What is your name ")
while not name.isalpha():
    print("invalid name")

age = input("What is your age ")
if not age.isdigit():
    print("Please type in correct form")
    if age >= "50":
    print("you are not allowed!")
    sys.exit()

item_1 = "burger"
item_2 = "pizza"
print("what would you like to order?")

print(item_1 + "\n" + item_2)
order = input()

item_1_large = "large burger"
item_1_small = "small burger"

item_2_large = "large pizza"
item_2_small = "small pizza"

if order == item_1:
    print("What would you like to choose?")
    print(item_1_large + "\n" + item_1_small)
    selection_of_category = input()
elif order == item_2:
    print("What would you like to choose?")
    print(item_2_large + "\n" + item_2_small)
    selection_of_category = input()

print("How many ")
number_of_order = input()

burger_price_large = int(10)
burger_price_small = int(5)
pizza_price_large = int(15)
pizza_price_small = int(8)




if order == item_1_large:
    result = burger_price_large * int(number_of_order)
elif order == item_1_small:
    result = burger_price_small * int(number_of_order)
elif order == item_2_large:
    result = pizza_price_large * int(number_of_order)
elif order == item_2_small:
    result = pizza_price_small * int(number_of_order)



if order == item_1:
    print("Your Burger Order Has Been Placed")
elif order == item_2:
    print("Your Pizza Order Has Been Placed")
else:
    print("You have made wrong choice")

print("Dear Mr. " + name, "Your Total Bill is $" + str (result))
while True:
main()
if input("Would you like to order something? (Y/N)").strip().upper() != 'Y':
    today = date.today()
    print("Thank you for your order")
    print(today)
    break

And i am having the following error print("Dear Mr. " + name, "Your Total Bill is $" + str (result)) UnboundLocalError: local variable 'result' referenced before assignment

1
None of the result = ... assignments in the code were executed before the print(...) line was called. So Python doesn't know what to do with the result variable, it has no value (not to mix up with None) - Michael Butscher

1 Answers

3
votes

Your issue is that result is only defined under if and else-if statements. This means that if every condition in if or else-if statements fails, result will not be defined, yet you will be trying to use its value.

You have two solutions to fix this issue:

  1. Make the last elif an else to be a catch-all and have a value for all possible values of order
  2. Have a separate else after the last elif to define result to something like "N/A" if all the if & elif conditions fail.