簡體   English   中英

Python錯誤,分配前可能會引用局部變量,if條件之外的變量

[英]Python Error, Local variable might be referenced before assignment, variable outside the if condition

我是python編程實踐的新手,做了我的第一個基本程序

我必須訪問並打印if函數中的局部變量,並且如果我嘗試訪問它,它表明可能引用了局部變量

這是完整的代碼

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

而且我有以下錯誤打印(“親愛的先生” +名稱,“您的總帳單為$” + str(結果))UnboundLocalError:賦值之前引用了局部變量'result'

您的問題是僅在if和else-if語句下定義結果。 這意味着,如果if或else-if語句中的每個條件都失敗,則不會定義結果,但是您將嘗試使用其值。

您有兩種解決此問題的方法:

  1. 使最后一個elif成為全包,並為所有可能的階值取一個值
  2. 如果所有if&elif條件均失敗,則在最后一個elif之后使用另一個else將結果定義為類似“ N / A”的內容。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM