2017-03-19 43 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")