網站首頁 編程語言 正文
本文實例為大家分享了python實現購物車小程序的具體代碼,供大家參考,具體內容如下
功能實現:
(1)可以查看購物車的商品,和余額
(2)可以顯示商品列表,根據商品的編號選擇商品
#定義一個列表存放商品信息 products=[('iphone',5800),('bike',220),('vivo',2000),('book',20)] shopping_list=[]#將購買的商品存在列表shopping_list 中 salary=input("輸入你的工資") #判斷輸入的工資是否是數字 if salary.isdigit(): ? ? salary=int(salary)#把輸入的工資轉換為整型 ? ? while True: ? ? ? ? # for i in products:輸出商品編號和商品信息兩種方式均可 ? ? ? ? # ? ? print(products.index(i),i) ? ? ? ? for index,i in enumerate(products): ? ? ? ? ? ? print(index,i) ? ? ? ? user_choice=input("選擇要買的商品") ? ? ? ? #通過輸入商品編號來選擇商品 ? ? ? ? if user_choice.isdigit(): ? ? ? ? ? ? user_choice=int(user_choice) ? ? ? ? ? ? if user_choice>=0 and user_choice<len(products): ? ? ? ? ? ? ? ? p_item=products[user_choice] ? ? ? ? ? ? ? ? if p_item[1]<=salary: ? ? ? ? ? ? ? ? ? ? shopping_list.append(p_item)#把買的東西放到購物車 ? ? ? ? ? ? ? ? ? ? salary-=p_item[1]#計算買完東西以后剩下的錢 ? ? ? ? ? ? ? ? ? ? print("add %s into shopping car,you current salary %s" %(p_item[0],salary)) ? ? ? ? ? ? ? ? else: ? ? ? ? ? ? ? ? ? ? print("\033[41;1m你的余額只剩[%s]了,不能買了,按q退出\033[0m" %salary) ? ? ? ? ? ? else: ? ? ? ? ? ? ? ? print("商品不存在") ? ? ? ? elif user_choice=='q': ? ? ? ? ? ? print("購物車的商品如下所示") ? ? ? ? ? ? for p in shopping_list: ? ? ? ? ? ? ? ? print(p) ? ? ? ? ? ? print("余額",salary) ? ? ? ? ? ? break ? ? ? ? else: ? ? ? ? ? ? print("invalid input") else: ? ? print("invalid input")
效果:
原文鏈接:https://www.cnblogs.com/come-on-baby/p/9480552.html
相關推薦
- 2022-10-30 C++解析obj模型文件方法介紹_C 語言
- 2023-07-16 unipp 小程序 退出登錄
- 2022-10-27 go?熔斷原理分析與源碼解讀_Golang
- 2022-06-16 golang配置管理神器Viper使用教程_Golang
- 2022-10-18 QT中QDataStream二進制數據讀寫的實現_C 語言
- 2022-07-02 Python列表1~n輸出步長為3的分組實例_python
- 2022-11-22 react?hooks實現原理解析_React
- 2022-08-06 Python結合spaCy?進行簡易自然語言處理_python
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支