2017-03-19 40 views
0

因此,我正在为我的大学做一个为python制作简单餐饮系统的任务。代码的一部分,其中的问题是:卡住了应用程序不接受输入的错误

def other_services(): 
    global servicesCart 
    services = [{"name":"1. Tent per 10 feet","price":400},{"name":"2. Chairs per 50 peices","price":50},{"name":"3. Tables per 10 pieces","price":80},{"name":"4. Table cloth per 10 peices","price":20}] 
    print("Press E to exit") 
    while True: 
     for f in services: 
      print("Name : ",f['name'],"Price : ",str(f['price'])) 
     selectedService = input("give your order") 
     if (selectedService == "E"): 
      cms() 
     try: 
      servicesCart.append(food_lunch[int(selectedService) - 1]) * (people) 
     except: 
      print("Wrong input, please try again.")} 

的问题是,无论我给什么输入,输出保持输入错误,请重试。这里的人数是代码开始时要求的客人数量,并且具有整数值。任何帮助都将非常有帮助。谢谢。

回答

2
servicesCart.append(food_lunch[int(selectedService) - 1]) * (people) 

不工作:要追加food_lunch[int(selectedService) - 1]append回报None和你乘以Nonepeople触发一个例外:既然你过滤所有例外

TypeError: unsupported operand type(s) for *: 'NoneType' and 'int' 

,你会得到你的错误信息,你会发现还有另一个错误:你必须得到“价格”字典键

修复:

try: 
     servicesCart.append(food_lunch[int(selectedService) - 1]["price"] * (people)] 
    except Exception as e: 
     print("{}, please try again.".format(e)) 

,所以如果有什么事情发生,你得到实际的错误信息,而不是你的通用(和错误的错误消息)

在这里,你可能想赶上IndexError从列表访问。我建议你使用len而不是try/catch块来检查边界。

idx = int(selectedService) - 1 
if 0 <= idx < len(food_lunch): 
    servicesCart.append(food_lunch[idx]["price"] * people) 
else: 
    print("invalid input") 

这已过滤负指标的优势,这将是愉快的[](名单接入端),只要其绝对值范围内,可能不是你想要的东西接受

+0

错误是“不受支持的操作数类型为*:'dict'和'int',请重试。” –

+0

至少try/catch块很有用:)见我的编辑。我忽略了你的数据类型 –

+0

好了,所以错误消失了,但价格没有加起来,这完全是奇怪的。选择后,各个数组应加起来总计在一起,然后到另一个具有全部总额的模块。当我看到报告时显示0,这意味着代码不计算数组的各个部分的整数值。希望它有道理大声笑。 –

0

      # printing your products : 

print("T for Tent\n C for chairs \n Ta for Tables \n Tac for clothes table") #list of your priducts : list_1 = {"T": " Tent per 10 feet its price : 400$","C": "Chairs per 50 peices its price: 50$","Ta" : "Tables per 10 pieces its price: 80$","Tac": "cloth table per 10 peices its price: 20$"}

      #calling customer order : 

while True: selectedService = input("give your order") if (selectedService == "E"): break elif selectedService in list_1: print(list_1[selectedService]) else: print("your request is not available")