2014-04-16 19 views
0

我是一個完整的初學者python3。我從wikibooks主頁 採取腳本,我改變了我的需要。問題是我不知道如何將腳本輸入單詞改爲數字(如'str'到'int'和'int'到'str')。Shoplist腳本和空列表數量?

更改的腳本:

shoplist = []

DEF主():

while True: 
    print() 
    print("---------") 
    print("Shopping:") 
    print("---------") 
    print() 
    print("(1)Add item: ") 
    print("(2)Remove item: ") 
    print("(3)Quit shopping: ") 
    print() 

    menu_item = int(input("\tChoose you shopping item number (1-3)?: ")) 

    if menu_item == 1: 
     name_add = input("\tWhat item you add?: ") 
     shoplist.append(name_add) 
    elif menu_item == 2: 
     print("\tThere are", str(shoplist).strip('['']'), "items in the list.") 
     name_del = input("\tWhich item you remove?: ") 
     if name_del in shoplist: 
      item_number = shoplist.index(name_del) 
      del shoplist[item_number] 
    elif menu_item == 3: 
     print("\tThe following items in the shopping list:") 
     print() 
     together = 0 
     if len(shoplist) > 0: 
      while together < len(shoplist): 
       print("\t\t", shoplist[together]) 
       together = together + 1 
     print() 
     break 
    else: 
     print("\tIncorrect selection!") 

if __name__ == "__main__": 
      main() 

腳本輸出:

購物:

(1)添加項目:
(2)刪除項目:
(3)退出購物:

選擇您的購物項目編號(1-3)?: 1
你加什麼項目?:番茄汁

購物:

(1)添加項目:
(2)刪除項目:
(3)退出購物:

選擇您的購物項目編號(1-3)?: 1
你加什麼項目?:伏特加

購物:

(1)添加項目:
(2)刪除項目:
(3)退出購物:

選擇你購物時輸入號碼(1-3)?:2
列表中有'番茄汁','伏特加'項目。
刪除哪一項?:伏特加

購物:

(1)添加項目:
(2)刪除項目:
(3)退出購物:

選擇您的購物項目編號(1-3)?:3
在購物列表中的下列項目:

番茄汁

如何更改購物部分「(2)刪除項目:」以數字計數?

結果應該是(實施例):

購物:

(1)添加項目:
(2)拆下項:
(3)退出購物:

選擇你要購物的商品編號(1-3)?:2
列表中有2項。
你可以刪除哪項?:1

注意!在購物2項計數:'番茄汁'= 0和'伏特加'= 1。 腳本中的其他內容保持不變。

也許是一個更好的解決方案,在python列表中使用.append,.remove,.pop,.index但我仍然不知道更好的方法。

回答

0

可以按如下方式編輯elif聲明:

elif menu_item == 2: 
    print("\tThere are", len(shoplist), "items in the list.") 
    name_del = input("\tWhich item you remove?: ") 
    if name_del in shoplist: 
     item_number = shoplist.index(name_del) 
     del shoplist[item_number] 
+0

sshashank124,現在劇本節「(2)刪除項:」工作,但我仍然有一個問題與腳本部分「(3)退出購物: 」。如果我從購物清單中刪除商品,該商品不會從'(3)退出購物:'中刪除。還剩下完好的番茄汁和伏特加。 – Antsupoeg

+0

@Antsupoeg,你有什麼問題(3)退出購物?請包括問題,然後在這裏發表評論,讓我知道。 – sshashank124

+0

(2)刪除項目: - 列表中有2個項目。您刪除哪個項目?:1(3)退出購物: - 購物清單中的以下項目:番茄汁伏特加。但它應該只是番茄汁。 – Antsupoeg