搜索
首页后端开发Python教程Python实现购物系统实例介绍

Python实现购物系统实例介绍

Sep 15, 2017 am 09:47 AM
python实例系统

下面小编就为大家带来一篇Python实现购物系统(示例讲解)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧

要求:

用户入口

1、商品信息存在文件里
2、已购商品,余额记录。

商家入口

可以添加商品,修改商品价格

Code:

商家入口:


# Author:P J J

import os

ps = '''
1 >>>>>> 修改商品
2 >>>>>> 添加商品
按q为退出程序
'''

# 打开两个文件,f文件为原来存取商品文件,f_new文件为修改后的商品文件
f = open('commodit', 'r', encoding='utf-8')
f_new = open('commodit_update', 'w+', encoding='utf-8')
file_list = f.readlines()

# 打印商品信息
while True:
 productslist = []
 # 从商品文件中读取出来的数据存放到productslist列表里
 for line in file_list:
  productname = line.strip().split()
  productname, oldprice = line.strip("\n").split()
  productslist.append([productname, int(oldprice)])
 choose = input("%s请选择:" %ps)
 if choose =='1':
  for index, item in enumerate(productslist):
   print(index, item)
  productindex = input("请输入要修改价格的商品序号:")
  if productindex.isdigit():
   productindex = int(productindex)
  while True:
   print('要修改商品信息:', productslist[productindex])
   price = input("请输入要修改的价格:")
   if price.isdigit():
    price = int(price)
    productslist[productindex][1]=price
    break
   else:
    print("请正确的输入价格!")
    continue

  #已经修改好的商品列表循环写入f_new文件夹

  for products in productslist:
   insert_data = "%s %s" %(products[0],products[1])
   f_new.write(insert_data+'\n')
  print("商品价格已经修改!")
  # 替换原来的文件
  f_new = open('commodit_update', 'r', encoding='utf-8')
  data = f_new.readlines()
  f = open('commodit', 'w+', encoding='utf-8')
  for line in data:
   f.write(line)
  f.close()
  f_new.close()
  #删除替换文件
  os.remove('commodit_update')
 elif choose =='2':
  # 添加商品
  f = open('commodit', 'a+', encoding='utf-8')
  pricename = input("请输入商品名:")
  while True:
   price = input("请输入商品价格:")
   if price.isdigit():
    f.writelines('%s %s\n' % (pricename, price))
    break
   else:
    print('输入错误请重新输入!')
    continue
  f.close()
  continue
 elif choose =='q':
  break
 else:
  print("输入错误请重新输入")
  continue

买家入口:


# Author:P J J

productslist = []
f = open('commodit','r',encoding='utf-8')
for line in f:
 productname,price = line.strip('\n').split()
 productslist.append((productname,int(price)))

print(productslist)
shopping_list = []

salary = input("请输入你的现金:")
if salary.isdigit():
 salary = int(salary)
 while True:
  # for item in productslist:
  #  print(productslist.index(item),item)
  for index,item in enumerate(productslist):
   print(index,item)
  #判断用户要输入
  user_choice = input("请选择要买什啥>>>:")
  if user_choice.isdigit():
   user_choice = int(user_choice)
   if user_choice < len(productslist) and user_choice >= 0:
    p_item = productslist[user_choice]
    if p_item[1] <= salary: #买得起
     shopping_list.append(p_item)
     salary -=p_item[1]
     print("加入 %s 购物车你的余额是\033[31;1m%s\033[0mRMB" %(p_item,salary))
    else:
     print("\033[32;1m 你的余额只剩[%s]RMB啦,还买个毛线\033[0m " %salary)
   else:
    print("\033[41;1m您输入的商品不存在,请重新输入!\033[0m")
  elif user_choice == &#39;q&#39;:
   print("----shopping_list----")
   for p in shopping_list:
    print(p)
   print("你的余额:\033[31;1m%s\033[0mRMB" %salary)
   #简单的余额记录
   f = open(&#39;salary&#39;,&#39;w+&#39;,encoding=&#39;utf-8&#39;)
   f.writelines(str(salary))
   f.close
   exit()
  else:
   print("错误选项")

操作流程:


我的目录:


1、新建一个文件,名为 commodit 商品排列格式如下(自己可以更改商品名字或者价格)

2、运行商家入口测试功能



我们输入1,首先测试修改商品:




输入0,修改第一个商品价格为400:



退出后查看 commodit 文件看见商品价格已经修改




--------------------------------------------------

测试添加商品:



查看 commodit文件




测试买家入口:



有钱了那就先来一台Iphone



再来60包炉石卡包



按q退出结账!并且有一个salary文件记录余额



此时目录会多一个salary文件



点开就能看到余额已经被记录

感想:

做完这个购物车花了2天,其实也不是整天都在弄,毕竟还要上课、学习。这次主要是熟悉文件的操作和一些基础知识的回顾,写完后能跑出功能就很开心了.因为中途遇到很多困难,解决了一个又出一个问题,不过通过上网查找和询问还是解决了。写完后感觉很low,毕竟自己敲得太少还是要多加练习,这个程序挺适合入门或者学完文件操作的亲来练练手。对了,自己测试程序的时候还出现bug,不过影响不是特别大,只是不要多次修改价格就行,这个问题我也想过怎么解决,就是把列表清空,这样数据就不会读出2遍,但又发现第二次读取的数据不是更改后的数据,我就在想,列表有没有刷新,清空功能。这里先留下这个问题吧。功能已经都实现了,但写的真的很low,等以后再掌握了新姿势,回头来改改!包括前面做的登录还有三级菜单!如果有跟我一样初学的可以一起学习Alex老师的python课程,如果有大神看到,并且能耐心看完,请大神再多指点指点小弟!

好了,Life is short,use python!

以上是Python实现购物系统实例介绍的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
可以在Python数组中存储哪些数据类型?可以在Python数组中存储哪些数据类型?Apr 27, 2025 am 12:11 AM

pythonlistscanStoryDatatepe,ArrayModulearRaysStoreOneType,and numpyArraySareSareAraysareSareAraysareSareComputations.1)列出sareversArversAtileButlessMemory-Felide.2)arraymoduleareareMogeMogeNareSaremogeNormogeNoreSoustAta.3)

如果您尝试将错误的数据类型的值存储在Python数组中,该怎么办?如果您尝试将错误的数据类型的值存储在Python数组中,该怎么办?Apr 27, 2025 am 12:10 AM

WhenyouattempttostoreavalueofthewrongdatatypeinaPythonarray,you'llencounteraTypeError.Thisisduetothearraymodule'sstricttypeenforcement,whichrequiresallelementstobeofthesametypeasspecifiedbythetypecode.Forperformancereasons,arraysaremoreefficientthanl

Python标准库的哪一部分是:列表或数组?Python标准库的哪一部分是:列表或数组?Apr 27, 2025 am 12:03 AM

pythonlistsarepartofthestAndArdLibrary,herilearRaysarenot.listsarebuilt-In,多功能,和Rused ForStoringCollections,而EasaraySaraySaraySaraysaraySaraySaraysaraySaraysarrayModuleandleandleandlesscommonlyusedDduetolimitedFunctionalityFunctionalityFunctionality。

您应该检查脚本是否使用错误的Python版本执行?您应该检查脚本是否使用错误的Python版本执行?Apr 27, 2025 am 12:01 AM

ThescriptisrunningwiththewrongPythonversionduetoincorrectdefaultinterpretersettings.Tofixthis:1)CheckthedefaultPythonversionusingpython--versionorpython3--version.2)Usevirtualenvironmentsbycreatingonewithpython3.9-mvenvmyenv,activatingit,andverifying

在Python阵列上可以执行哪些常见操作?在Python阵列上可以执行哪些常见操作?Apr 26, 2025 am 12:22 AM

Pythonarrayssupportvariousoperations:1)Slicingextractssubsets,2)Appending/Extendingaddselements,3)Insertingplaceselementsatspecificpositions,4)Removingdeleteselements,5)Sorting/Reversingchangesorder,and6)Listcomprehensionscreatenewlistsbasedonexistin

在哪些类型的应用程序中,Numpy数组常用?在哪些类型的应用程序中,Numpy数组常用?Apr 26, 2025 am 12:13 AM

NumPyarraysareessentialforapplicationsrequiringefficientnumericalcomputationsanddatamanipulation.Theyarecrucialindatascience,machinelearning,physics,engineering,andfinanceduetotheirabilitytohandlelarge-scaledataefficiently.Forexample,infinancialanaly

您什么时候选择在Python中的列表上使用数组?您什么时候选择在Python中的列表上使用数组?Apr 26, 2025 am 12:12 AM

useanArray.ArarayoveralistinpythonwhendeAlingwithHomeSdata,performance-Caliticalcode,orinterFacingWithCcccode.1)同质性data:arrayssavememorywithtypedelements.2)绩效code-performance-clitionalcode-clitadialcode-critical-clitical-clitical-clitical-clitaine code:araysofferferbetterperperperformenterperformanceformanceformancefornalumericalicalialical.3)

所有列表操作是否由数组支持,反之亦然?为什么或为什么不呢?所有列表操作是否由数组支持,反之亦然?为什么或为什么不呢?Apr 26, 2025 am 12:05 AM

不,notalllistoperationsareSupportedByArrays,andviceversa.1)arraysdonotsupportdynamicoperationslikeappendorinsertwithoutresizing,wheremactssperformance.2)listssdonotguaranteeconeeconeconstanttanttanttanttanttanttanttanttimecomplecomecomecomplecomecomecomecomecomecomplecomectaccesslikearrikearraysodo。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 英文版

SublimeText3 英文版

推荐:为Win版本,支持代码提示!

mPDF

mPDF

mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

将Eclipse与SAP NetWeaver应用服务器集成。