Python基於數列實現購物車程式過程詳解
阿新 • • 發佈:2020-06-10
要求
1、啟動程式後讓使用者輸入餘額,並列印商品列表
2、使用者通過輸入編號購買商品
3、使用者選擇商品購買後,根據餘額判斷成功或者失敗,給出對應提示
4、可以隨時退出,退出後列印賬號餘額以及購買的商品列表
構思
1、首先,使用者餘額需要進行儲存,使用者購買的物品需要進行儲存在陣列中
2、使用者購買成功後,將購買的物品放入物品集合,並用總金額減去餘額
3、如果失敗,給出失敗提示,並列印餘額
4、使用者選擇繼續後,無論成功失敗,都可以繼續購買
程式碼
# 使用者輸入工資 balance = int(input("Please input balance:")) # 定義衣服的陣列 clothes = [["pants",100],["T-shirt",50],["skirt",20]] # 個人所得,包括金錢和獲取的物品 haveGoods = [balance,[]] flag = True while flag: # 列印衣服列表 print("The clothes list is as follows") print("______clothesList______") i = 1; for c in clothes: print('The number:',i,":",c) i += 1 # 使用者輸入商品編號 code = int(input("Please choose the number:")) # 判斷錢是否夠用 if clothes[code-1][1] <= haveGoods[0]: # 在自己的購物清單中加入已購物品 haveGoods[1].append(clothes[code-1]) # 減去花費的金錢 haveGoods[0] -= clothes[code-1][1] print("You have successfully purchased!") print("Your account balance is:",haveGoods[0]) else: print("Your account balance is insufficient!") print("Your account balance is:",haveGoods[0]) judge = input("You can press any button to continue,or input 'n' to leave:") if judge == "n": flag = False print("Your account balance is:",haveGoods[0]) print("Your shopping list is as follows:") print("______clothesList______") for h in haveGoods[1]: print(h)
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。