这篇文章主要为大家详细介绍了Python3实现购物车功能,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
本文实例为大家分享了Python3实现购物车功能的具体代码,供大家参考,具体内容如下
购物车要求:
1、启动程序后,输入用户名密码后,如果是第一次登录,让用户输入工资,然后打印商品列表
2、允许用户根据商品编号购买商品
3、用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒
4、可随时退出,退出时,打印已购买商品和余额
5、在用户使用过程中, 关键输出,如余额,商品已加入购物车等消息,需高亮显示
6、用户下一次登录后,输入用户名密码,直接回到上次的状态,即上次消费的余额什么的还是那些,再次登录可继续购买
7、允许查询之前的消费记录
逻辑图:
执行代码:
#!/usr/bin/env python3 # Author: Robert # --*-- coding: utf-8 --*-- set = False #设置set 当输入为q就可以退出 file = open("购物车用户信息档案.txt","r+",encoding="utf-8") #读取购物车用户信息文件 f = str(file.read()) #将文件内容转化成字符串 for line in f: file_str = str(f) data = eval(file_str) #将字符串转换为字典data name = input("输入姓名:") password = input("输入密码:") while True: if name in data: #用户在档案中 if password in data[name]: #密码和用户名对应,校验正确,登录。 salary = float(data[name][password]) print('''\033[32;1m欢迎登录,当前余额为%s\033[0m'''%salary) break else: #否则密码错误,请重新输入 password = input("密码错误,请重新输入:") continue else: #否则判断为首次登录,将用户名,密码,工资存到用户信息文件中 password_salary = {} salary_str = input("欢迎首次登录,请输入你的工资:") salary = float(salary_str) password_salary[password] = salary #工资对应到密码 data[name] = password_salary #将密码-工资对应到用户名 file.seek(0) file.write(str(data)) file.tell() break list = [#购物清单 ["iphone",5800], ["sifei",800], ["macbook",17500], ["book",75], ["apple",5] ] file_list_r = open("历史购物信息.txt","r+",encoding="utf-8") file_list_r = str(file_list_r.read()) shoppinglist_dict = eval(file_list_r) if name not in shoppinglist_dict: shoppinglist_dict[name] = [] shoppinglist = shoppinglist_dict[name] shoppinglist_dict_now = [] choose = input("\n是否需要查询历史购物记录(y/n):") if choose == 'y': print("\n\n---------->历史购物记录<----------") print(shoppinglist) print("---------->结束<----------") while not set: #购物车开始 print("---------->商品清单<----------") for index,item in enumerate(list,1): print(index,item) print("---------->结束<----------") number = input("请输入想购买商品编号:") if number == "q": set = True data[name][password] = str(salary) file.seek(0) file.write(str(data)) file.tell() print("---------->购物清单<----------") print(shoppinglist) print("您的余额:",salary) print("---------->结束<----------") shoppinglist.extend(shoppinglist) shoppinglist_dict[name] = shoppinglist elif number.isdigit() == False: print("\033[31;1m输入不是编号内容,请重新输入\033[0m") elif int(number)>int(len(list)) or int(number)<= 0: #输入值不在清单中,报错 print("\033[31;1m您所购买的商品不在清单中\033[0m") else: number_buy = int(number)-1 if list[number_buy][1]<(salary): #如果余额足够,提示购买成功并显示余额。 salary = salary - int(list[number_buy][1]) msg = '\033[32;1m您已经将%s加入购物车中,余额为%d\033[0m'%(list[number_buy][0],salary) print(msg) shoppinglist.append(list[number_buy]) #将本次购物信息加到购买记录中 else: print("\033[31;1m余额不足,无法购买!\033[0m") #提示余额不足
购物车用户信息档案.txt
{'name': {'password': '10000'}, 'cx': {'123': '725.0'}, 'robert': {'qw': '440.0'}, 'cv1': {'1': 100.5}, 'ROBERT': {'QW': 1560.0}, 'qwe': {'qw': '1555.0'}}
历史购物信息.txt
{'name': [['iphone', 5800],['bike', 800]], 'cx':[['iphone', 5800],['apple', 5],['apple', 5], ['book', 75]]}
相关推荐:
以上がPython3でショッピングカート機能を実装の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

Pythonlistscanstoreanydatatype,arraymodulearraysstoreonetype,andNumPyarraysarefornumericalcomputations.1)Listsareversatilebutlessmemory-efficient.2)Arraymodulearraysarememory-efficientforhomogeneousdata.3)NumPyarraysareoptimizedforperformanceinscient

heouttemptemptostoreavure ofthewrongdatatypeinapythonarray、yure counteractypeerror.thisduetothearraymodule'sstricttypeeencultionyを使用します

PythonListSarePartOfThestAndardarenot.liestareBuilting-in、versatile、forStoringCollectionsのpythonlistarepart。

theScriptisrunningwithwrongthonversionduetorectRectDefaultEntertersettings.tofixthis:1)CheckthedededefaultHaulthonsionsingpython - versionorpython3-- version.2)usevirtualenvironmentsbycreatingonewiththon3.9-mvenvmyenv、andverixe

PythonArraysSupportVariousoperations:1)SlicingExtractsSubsets、2)Appending/ExtendingAdddesements、3)inSertingSelementSatspecificpositions、4)remvingingDeletesements、5)sorting/verversingsorder、and6)listenionsionsionsionsionscreatenewlistsebasedexistin

numpyarraysAressertialentionsionceivationsefirication-efficientnumericalcomputations andDatamanipulation.theyarecrucialindatascience、mashineelearning、物理学、エンジニアリング、および促進可能性への適用性、scaledatiencyを効率的に、forexample、infinancialanalyyy

UseanArray.ArrayOverAlistinPythonは、Performance-criticalCode.1)homogeneousdata:araysavememorywithpedelements.2)Performance-criticalcode:Araysofterbetterbetterfornumerumerumericaleperations.3)interf

いいえ、notallistoperationSaresuptedbyarrays、andviceversa.1)arraysdonotsupportdynamicoperationslikeappendorintorintorinsertizizing、whosimpactsporformance.2)リスト


ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

Video Face Swap
完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

人気の記事

ホットツール

SublimeText3 Mac版
神レベルのコード編集ソフト(SublimeText3)

DVWA
Damn Vulnerable Web App (DVWA) は、非常に脆弱な PHP/MySQL Web アプリケーションです。その主な目的は、セキュリティ専門家が法的環境でスキルとツールをテストするのに役立ち、Web 開発者が Web アプリケーションを保護するプロセスをより深く理解できるようにし、教師/生徒が教室環境で Web アプリケーションを教え/学習できるようにすることです。安全。 DVWA の目標は、シンプルでわかりやすいインターフェイスを通じて、さまざまな難易度で最も一般的な Web 脆弱性のいくつかを実践することです。このソフトウェアは、

EditPlus 中国語クラック版
サイズが小さく、構文の強調表示、コード プロンプト機能はサポートされていません

SecLists
SecLists は、セキュリティ テスターの究極の相棒です。これは、セキュリティ評価中に頻繁に使用されるさまざまな種類のリストを 1 か所にまとめたものです。 SecLists は、セキュリティ テスターが必要とする可能性のあるすべてのリストを便利に提供することで、セキュリティ テストをより効率的かつ生産的にするのに役立ちます。リストの種類には、ユーザー名、パスワード、URL、ファジング ペイロード、機密データ パターン、Web シェルなどが含まれます。テスターはこのリポジトリを新しいテスト マシンにプルするだけで、必要なあらゆる種類のリストにアクセスできるようになります。

WebStorm Mac版
便利なJavaScript開発ツール

ホットトピック









