You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python代码遇UnboundLocalError:cost未定义问题求助

披萨店订单管理代码UnboundLocalError问题排查与解决

问题重现

用户编写的披萨店订单管理代码如下:

print("============================================================\n"      
      "                 Welcome to Pizza Store                              \n"      
      "============================================================\n")
def welcomescreen():    
    print("1) Menu for the Pizza")    
    print("2) Order the Pizza")    
    print("3) Exit the program")    
    ch = input("Select from one of the above: ")    
    return ch
def main():    
    choice = welcomescreen()    
    while choice != '3':            
        # based on user choice add appropriate method        
        if choice == '1':            
            print("1. Pepperoni               9 AED\n2. Margherita              12 AED\n3. Vegetarian              15 AED\n4. Neapolitan              21 AED")            
            ask = input("Do you want to go back to the main menu? yes/no : \n").lower()            
            if ask == "yes":                
                main()            
            elif ask == "no":                
                break        
        elif choice == '2':            
            n=int(input("Enter the number of pizzas to be ordered: "))            
            kind=input("Enter the kind of Pizza: ")            
            size=input("Enter the size of Pizza\n(Large (50 AED),Medium (40 AED), Small (30 AED) : ")            
            if(size == "Large"):                
                cost_size=n*50            
            elif(size == "Medium"):                
                cost_size=n*40            
            elif(size == "Small"):                
                cost_size = n*30            
            if(kind == "Pepperoni"):              
                cost= n*10              
                pizza = 'Pepperoni'            
            elif(kind== "Margherita" ):                
                cost= n*15                
                pizza = "Margherita"            
            elif(kind == "Vegetarian" ):                
                cost= n*20                
                pizza = "Vegetarian"            
            elif(kind== "Neapolitan"):                
                cost= n*18                
                pizza = "Neapolitan"            
            d=input("Enter toppings: \n").split(" ")            
            extra=0            
            if(len(d)>3):                 
                extra= n*3*(len(d)-3)#final Bill            
            print("---------------------Your BILL-----------------------\n")            
            print("The Pizza kind :", kind)            
            print("The size :", size)            
            print("Number of pizzas :  x", n)            
            print("Extra toppings :")            
            for i in d:                
                print(i,end=" ")            
            print("\n")            
            print("==========Breakdown of bill========== \n")            
            print("Bill for pizza         : ", cost)            
            print("Bill for size         : ",cost_size)            
            print("Bill for extra toppings: ",extra)            
            print("Total Bill             : ",cost+cost_size+extra)        
        else:            
            print("Invalid choice. Try again.")        
        choice = welcomescreen()    
    print("Thank you! Have a nice day :)")
main()

运行时触发UnboundLocalError,错误信息:

Exception has occurred: UnboundLocalError
cannot access local variable 'cost' where it is not associated with a value  
File "C:\Users\mandoof1\Downloads\Pizza part A.py", line 57, in main    
    print("Bill for pizza         : ", cost)  
File "C:\Users\mandoof1\Downloads\Pizza part A.py", line 68, in <module>    
    main()

错误原因

  • 核心问题:cost变量仅在用户输入的披萨种类匹配预设的四种时才会被赋值,若输入的种类不在列表中(比如拼写错误、输入其他种类),所有if/elif分支都不会执行,cost变量从未被定义,但后续代码直接调用该变量,导致UnboundLocalError。
  • 隐藏风险:cost_size变量存在同样问题,若用户输入的尺寸不是Large/Medium/Small,也会触发相同错误。

解决方案

  1. 初始化cost和cost_size为默认值,同时添加非法输入的判断逻辑,提示用户输入错误并终止当前订单流程。
  2. 优化菜单展示,引导用户输入正确的披萨种类和尺寸,避免无效输入。

修正后的代码

print("============================================================\n"      
      "                 Welcome to Pizza Store                              \n"      
      "============================================================\n")
def welcomescreen():    
    print("1) Menu for the Pizza")    
    print("2) Order the Pizza")    
    print("3) Exit the program")    
    ch = input("Select from one of the above: ")    
    return ch

def main():    
    choice = welcomescreen()    
    while choice != '3':            
        if choice == '1':            
            print("1. Pepperoni               9 AED\n2. Margherita              12 AED\n3. Vegetarian              15 AED\n4. Neapolitan              21 AED")            
            ask = input("Do you want to go back to the main menu? yes/no : \n").lower()            
            if ask == "yes":                
                # 避免递归调用main,改用循环控制
                choice = welcomescreen()
            elif ask == "no":                
                break        
        elif choice == '2':            
            n=int(input("Enter the number of pizzas to be ordered: "))            
            kind=input("Enter the kind of Pizza (Pepperoni/Margherita/Vegetarian/Neapolitan): ")            
            size=input("Enter the size of Pizza (Large/Medium/Small): ")            
            # 初始化变量,避免未赋值报错
            cost_size = 0
            cost = 0
            pizza = ""
            
            # 处理尺寸逻辑
            if size == "Large":                
                cost_size = n * 50            
            elif size == "Medium":                
                cost_size = n * 40            
            elif size == "Small":                
                cost_size = n * 30            
            else:
                print("Invalid size entered! Please try again.")
                # 跳过后续账单流程,回到主菜单
                choice = welcomescreen()
                continue
            
            # 处理披萨种类逻辑
            valid_kind = True
            if kind == "Pepperoni":              
                cost = n * 10              
                pizza = 'Pepperoni'            
            elif kind == "Margherita":                
                cost = n * 15                
                pizza = "Margherita"            
            elif kind == "Vegetarian":                
                cost = n * 20                
                pizza = "Vegetarian"            
            elif kind == "Neapolitan":                
                cost = n * 18                
                pizza = "Neapolitan"            
            else:
                print("Invalid pizza kind entered! Please try again.")
                valid_kind = False
            
            if not valid_kind:
                # 输入无效,回到主菜单
                choice = welcomescreen()
                continue
            
            # 处理配料逻辑
            d = input("Enter toppings (separated by space): \n").split()
            # 过滤空字符串(用户可能输入多个空格)
            d = [topping for topping in d if topping.strip()]
            extra = 0            
            if len(d) > 3:                 
                extra = n * 3 * (len(d) - 3)
            
            # 生成账单
            print("\n---------------------Your BILL-----------------------")            
            print(f"The Pizza kind : {pizza}")            
            print(f"The size : {size}")            
            print(f"Number of pizzas :  x{n}")            
            print("Extra toppings :", ", ".join(d) if d else "None")            
            print("\n==========Breakdown of bill==========")            
            print(f"Bill for pizza         : {cost} AED")            
            print(f"Bill for size          : {cost_size} AED")            
            print(f"Bill for extra toppings: {extra} AED")            
            print(f"Total Bill             : {cost + cost_size + extra} AED\n")        
        else:            
            print("Invalid choice. Try again.")        
        choice = welcomescreen()    
    print("Thank you! Have a nice day :)")

main()

修改说明

  • 初始化cost和cost_size变量,避免未赋值报错
  • 添加非法输入判断,当用户输入无效的披萨种类或尺寸时,提示错误并终止当前订单
  • 优化配料处理,过滤空字符串,避免用户输入空格导致的无效配料计数
  • 替换递归调用main()为循环控制,避免栈溢出风险
  • 使用f-string优化账单输出格式,可读性更强

内容的提问来源于stack exchange,提问作者Helpiamnew

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 17:55:30