python實現購物車腳本


使用python3實現的簡單購物車程序

用戶入口
1、第一次需要輸入自己的金額,下次購買會記錄上一次所剩的余額
2、用戶只需要輸入對應商品前面的序號即可將商品添加進購物車
3、能夠記錄用戶購買商品的歷史記錄,並每次退出程序后顯示總的購買情況

商家入口
1、商家需要通過賬號驗證進入
2、商家能夠對商品進行添加以及修改商品的價格

可以自行考慮一些其余的功能添加上去

 

  1 #!/usr/bin/env python
  2 #coding:utf-8
  3 
  4 import os
  5 
  6 def text_save(filename, data):  ##定義函數將列表存入到文件里面
  7     file = open(filename,'w')
  8     for i in range(len(data)):
  9         s = str(data[i]).replace('[','').replace(']','')
 10         s = s.replace("'",'').replace(',','') +'\n'
 11         file.write(s)
 12     file.close()
 13 
 14 size = os.path.getsize('shopping.txt')  #判斷存商品的文件是否為空,如果為空,則使用自定義的商品初始值
 15 if size == 0:
 16      shopping = [['phone',2800],['snacks',200],['watch',1200],['cloths',500]]
 17 else:
 18     shopping = []
 19     with open('shopping.txt','r') as f:
 20         for data in f.readlines():
 21            shopping.append(data.split(' '))
 22     for data2 in range(len(shopping)):
 23         shopping[data2][1] = shopping[data2][1].rstrip('\n')
 24         shopping[data2][1] = int(shopping[data2][1])
 25 
 26 
 27 shopping_list = []  #定義用戶購買的商品列表
 28 
 29 
 30 with open('shopping_cart.txt','r') as f1:  #打開存取用戶商品的文件,並將已購買的商品讀取保存到列表里
 31     for j in f1.readlines():
 32         shopping_list.append(j.split(' '))
 33 for j2 in range(len(shopping_list)):
 34     shopping_list[j2][1] = shopping_list[j2][1].rstrip('\n')
 35 
 36 
 37 with open('user.txt','r') as f: #需要事先在文件里面寫上驗證的用戶,這里只定義了一個admin用戶,用於區分是用戶還是商家
 38     userlist = f.readlines()
 39 for i in range(len(userlist)):
 40     userlist[i] = userlist[i].strip('\n')
 41 
 42 
 43 role  = input('if or not  you are admin?(y|n):')  #簡單判斷是進入到用戶入口還是商家入口
 44 
 45 #用戶入口
 46 if role  == 'n':
 47     size = os.path.getsize('salary.txt') #若保存工資的文件為空,則需要用戶手動輸入自己的余額,否則直接讀取里面保存的余額
 48     if size == 0:
 49         money = input('please input your RMB:')
 50     else:
 51         with open('salary.txt','r') as f3:
 52             money = f3.read()
 53     flag1 = False
 54     if money.isdigit():
 55         money = int(money)
 56         while not flag1:
 57             for index,item in enumerate(shopping):#獲取商品的列表以及對應的下標,用戶選擇對應的序號即可添加商品到購物車
 58                 print(index,item)
 59             product_choice = input("你需要選擇什么商品>>>")
 60             if product_choice.isdigit():
 61                 product_choice = int(product_choice)
 62                 if product_choice < len(shopping) and product_choice >=0:#判斷選擇購買的商品是否在列表里存在
 63                     product_item = shopping[product_choice]
 64                     if product_item[1] <= money: #判斷余額是否足夠
 65                         shopping_list.append(product_item)
 66                         money -= product_item[1]
 67                         print("add [%s] into your shopping cart and Your remaining balance is \033[31;1m%s\033[0m" %(product_item[0],money))
 68                     else:
 69                         print("\033[41;1m你的余額不足,請及時充值...\033[0m")
 70                 else:
 71                     print("沒有這個商品,請選擇其余物品...")
 72     
 73             elif product_choice == 'q':
 74                 print('''
 75     ----------------------
 76     你的購物車當前的商品有:''')
 77                 for i in shopping_list:
 78                     print(i)
 79                 print("your remaining balance is",money)
 80                 flag1 = True
 81             else:
 82                 print("invalid input")
 83     with open('salary.txt','w') as f4:
 84         f4.write(str(money))
 85     text_save('shopping_cart.txt',shopping_list)
 86  
 87 
 88 #商家入口   
 89 elif role == 'y':
 90     flag = False
 91     i = 0
 92     while not flag:
 93         user = input('please input your admin user:')
 94         print(user,type(user))
 95         if user  in userlist:
 96             while not flag:
 97                 i = 0 
 98                 change = input("do you want to modify shopping?(y|n):")
 99                 if change == 'y':
100                     while not flag:
101                         change1 = input("add shopping(1) or modify shopping price(2),(1|2|q):")  #通過判斷商家是需要添加商品還是修改商品價格,或者可以直接退出
102                         if change1 == '1':
103                             add_shop = input('please input shopping that you want to add!')
104                             shop_price = input('please input shopping price!')
105                             shopping.append([add_shop,shop_price])
106                         elif change1 == '2':
107                             for index1,item1 in enumerate(shopping):  #獲取到需要修改的商品對應的列表和下標
108                                print(index1,item1)
109                             mod_shopping = input('what shopping price do you want to modify?')
110                             if mod_shopping.isdigit(): #判斷輸入的是否為數字,並且將字符串類型轉換為int
111                                 mod_shopping = int(mod_shopping) 
112                             change_shopping = shopping[mod_shopping][0]
113                             mod_price = input('how much do you want to change?')
114                             if mod_price.isdigit(): #默認輸入的價格是str類型,需要轉換為int
115                                 mod_price = int(mod_price)
116                             shopping[mod_shopping] = [change_shopping,mod_price]
117                         elif change1 == 'q':
118                             print("exiting...")
119                             flag = True
120                         else:
121                             print("invalid option...")
122                 elif change == 'n':
123                     print("正在退出管理商品終端...")
124                     flag = True
125                 else:
126                     pass        
127         else:
128             print('您的驗證錯誤,請重新輸入正確的用戶:')
129             i = i+1
130             if i >= 3:
131                 print('你已經連續輸錯了三次,將自動退出。。')
132                 flag = True
133     text_save('shopping.txt',shopping)
134 
135 else:
136     print('invalid option...')

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM