Python学习day2作业总结

简介:
为了以后更好更快速的复习,此博客记录我对作业的总结。对于基础作业,我认为最重要的是过程,至于实现是不是完美,代码是不是完美,虽然重要,但是作业过程中,用到的知识点是值得总结和整理的。

一.购物车:

1. 商品信息- 数量、单价、名称  
2. 用户信息- 帐号、密码、余额  
3. 用户可充值  
4. 购物历史信息  
5. 允许用户多次购买,每次可购买多件  
6. 余额不足时进行提醒  
7. 用户退出时 ,输出当次购物信息  
8. 用户下次登陆时可查看购物历史  
9. 商品列表分级显示

思路:

1.此作业是day1作业的结合体;

2.用户登录是否首次,分为新用户和旧用户;

3.旧用户查看是否有购物历史;

4.购买时可输入购买数量;

5.余额大于等于购买商品花费则购买成功,购买成功记录购买信息;

6.余额小于购买商品花费则提示充值,要求输入充值金额;

6.购物车自动整理购物商品与花费;

7.可随时查看购物车;

基本流程图:

完美购物车

代码:

1
cat  shopping_cart.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
#!/usr/bin/env python
# _*_coding:utf-8_*_
'''
  * Created on 2016/10/18 22:01.
  * @author: Chinge_Yang.
'''
import  os
import  getpass
import  datetime
menu  =  {
     "Mobile phone" : [
         ( "Iphone7" 6188 ),
         ( "Iphone7 plus" 7888 ),
         ( "Xiaomi5" 2888 )
     ],
     "Car" : [
         ( "Audi Q5" 490000 ),
         ( "Ferrari 488" 4888888 )
     ],
     "Drink" : [
         ( "Milk" 59 ),
         ( "Coffee" 30 ),
         ( "Tea" 311 )
     ]
}
user_file  =  "user.txt"
shopping_log  =  "shopping.log"
money  =  0    #初始金额
all_cost  =  0
shopping_cart  =  {}
exit_user_flag  =  False
exit_flag  =  False
exsit_flag  =  False
if  not  os.path.exists(user_file):
     =  open (user_file, 'w' )
     f.close()
if  not  os.path.exists(shopping_log):
     =  open (shopping_log, 'w' )
     f.close()
def  show_shopping_cart ():     #显示购物车,更新用户信息,exit前使用
     #显示购物车信息
     print ( "You purchased products as below" .center( 50 , "*" ))
     print ( "%-20s %-15s %-10s %-20s"  % ( "Goods" , "Price" , "Number" , "Cost" ))
     for  key  in  shopping_cart:
         p_name  =  key[ 0 ]
         p_price  =  int (key[ 1 ])
         p_number  =  int (shopping_cart[key])
         print ( "%-20s %-15s %-10s \033[32;1m%-20s\033[0m"  % (p_name,p_price,p_number,p_price * p_number))
     print ( "End" .center( 50 , "*" ))
     print ( "%-20s %-15s %-10s \033[32;1m%-20s\033[0m"  % ( "You total cost:" ," "," ",all_cost))
     print ( "Your balance is [\033[32;1m%s\033[0m]"  %  money)
     if  new_user  is  True :
         # 将新用户信息写入到用户文件中
         file  =  open (user_file,  "a" )
         file .write( "%s %s %s\n"  %  (user_name, user_passwd, money))   # 用户、密码、金钱存入用户文件
         file .close()
     else :
         if  old_money ! =  money:   #充值或买了东西
             # 将旧用户信息更新到用户文件中
             old_user_info  =  "%s %s %s"  %  (user_name, user_passwd, old_money)
             new_user_info  =  "%s %s %s"  %  (user_name, user_passwd, money)
             with  open (user_file) as  file :
                 info  =  file .read()
             new_info  =  info.replace(old_user_info,new_user_info)
             with  open (user_file, "w" ) as  file :
                 file .write(new_info)
while  exit_user_flag  is  not  True :
     #输入用户密码
     user_name  =  input ( "Please input your name:" ).strip()
     #user_passwd = input("Please input your password:").strip()
     user_passwd  =  getpass.getpass( "\033[1;33mPlease input your password:\033[0m" )
     if  user_name  = =  ' ' or user_passwd == ' ':
         continue
     elif  ' '  in  user_name:
         print ( "\033[31;1mNot allowed to contain spaces!\033[0m" )
         continue
     #查看是否存在于用户数据库
     user_check  =  open (user_file)
     for  in  user_check:
         =  l.split()
         user  =  l[ 0 ]
         passwd  =  l[ 1 ]
         if  user_name  = =  user:    #老用户
             new_user  =  False     #标记为老用户
             money  =  int (l[ 2 ])    #记录用户余额
             old_money  =  money    #旧余额
             if  not  passwd  = =  user_passwd:
                 print  ( "\033[1;31mYour password is error!\033[0m" .center( 50 , "*" ))
             else :
                 print  ( "\033[1;31mWelcome to go shopping!\033[0m" .center( 50 , "-" ))
                 exit_user_flag  =  True
             break
     else :
         new_user  =  True  #标记为新用户
         exit_user_flag  =  True
     user_check.close()   #关闭
if  not  new_user:     #旧用户
     #读取购物历史,判断是否有此用户记录
     file  =  open (shopping_log)
     for  line  in  file :
         line  =  line.split()
         line_user  =  line[ 0 ]
         if  line_user  = =  user_name:   #存在记录
             exsit_flag  =  True
             break    #跳出检测
     file .close()
     if  exsit_flag  is  True :    #内容不为空
         #只有输入y或者yes才读取显示购物历史,否则不显示
         print ( "Input \033[1;33m[y|yes]\033[0m to view your purchase history,\033[1;33m[others]\033[0m means not." )
         see_history  =  input ( "Please input:" ).strip()
         if  see_history  = =  "y"  or  see_history  = =  "yes" :
             # 显示用户购物历史
             # output = os.system("grep %s %s" %(user_name,shopping_log))
             # print(output.read())
             print ( "User %s shopping history:"  %  user_name)
             print ( "%-20s %-15s %10s %20s"  % ( "Username" , "datetime" , "Number" , "Goods" ))
             file  =  open (shopping_log)
             for  line  in  file :
                 line  =  line.split( "\t" )
                 line_user  =  line[ 0 ]
                 if  line_user  = =  user_name:   #存在记录
                     print ( "%-10s %-15s %10s %20s"  %  (line[ 0 ],line[ 1 ],line[ 2 ],line[ 3 ].strip()))
             file .close()
         else :
             print ( "You are not to view your purchase history!" )
             print ( "-" .center( 50 , "-" ))
one_layer_list  =  []  #一级菜单
while  True :
     while  True :
         #打印各类菜单
         print ( "Species list" .center( 50 , "-" ))
         for  index, item  in  enumerate (menu):
             print ( "\033[32;1m%d\033[0m --> %s"  %  (index, item))
             one_layer_list.append(item)
         print ( "End" .center( 50 , "-" ))
         print ( "[q|b] to quit" )
         once_choice  =  input ( "Input your choice:" ).strip()
         if  once_choice.isdigit():    #输入数字
             once_choice  =  int (once_choice)
             if  0  < =  once_choice <  len (menu):     #输入正确数字
                 print ( "---->Enter \033[32;1m%s\033[0m"  % (one_layer_list[once_choice]))
                 two_layer_list  =  menu[one_layer_list[once_choice]]
                 exit_flag  =  False    #重新进入二级商品菜单
                 break    #跳出循环,往下走
             else :
                 print ( "\033[31;1mNumber out of range, please enter again!\033[0m" )
         else :
             if  once_choice  = =  "b"  or  once_choice  = =  "back"  or  once_choice  = =  "q"  or  once_choice  = =  "quit" :
                 show_shopping_cart()
                 exit( "Bye,thanks!" .center( 50 , "#" ))
             print ( "\033[31;1mPlease enter the Numbers!\033[0m" )
     while  exit_flag  is  not  True :
         #显示二级商品菜单
         print ( "Product list" .center( 50 , '-' ))
         for  item  in  enumerate (two_layer_list):
             index  =  item[ 0 ]
             p_name  =  item[ 1 ][ 0 ]
             p_price  =  item[ 1 ][ 1 ]
             print ( "%s.%-20s %-20s"  % (index,p_name,p_price))
         print ( "End" .center( 50 , '-' ))
         print ( "[q|quit] to quit;[b|back] to back" )
         user_choice  =  input ( "Please choice the product:" ).strip()
         if  user_choice.isdigit():    #输入数字
             user_choice  =  int (user_choice)
             if  0  < =  user_choice <  len (two_layer_list):
                 product_number  =  input ( "Please input the number of product:" ).strip()    #输入个数
                 if  product_number.isdigit():
                     product_number  =  int (product_number)
                 else :
                     continue     #重新选择商品和个数
                 p_item  =  two_layer_list[user_choice]
                 p_name  =  p_item[ 0 ]   #商品名
                 p_price  =  int (p_item[ 1 ])     #商品价格
                 new_added  =  {}
                 if  p_price * product_number < =  money:  #能付款,表示购买成功
                     new_added  =  {p_item:product_number}
                     #整理购物车个数显示总数
                     for  k, v  in  new_added.items():
                         if  in  shopping_cart.keys():
                             shopping_cart[k]  + =  v
                         else :
                             shopping_cart[k]  =  v
                     money  - =  p_price  *  product_number
                     all_cost  + =  p_price  *  product_number
                     print ( "Added [\033[32;1m%d\033[0m] [\033[32;1m%s\033[0m] into shopping cart,"
                           "your balance is [\033[32;1m%s\033[0m]"  %  (product_number,p_name,money))
                     with  open (shopping_log, "a" ) as  file :
                         log  =  "%s\t\"%s\"\t%d\t\"%s\"\n"  % (user_name,datetime.datetime.now().strftime( '%Y-%m-%d %H:%M:%S' ),product_number,p_name)
                         shopping_history  =  file .write(log)
                 else :
                     #钱不够时,提示充值
                     print ( "Your balance is [\033[31;1m%s\033[0m],cannot afford this.."  %  money)
                     while  True :
                         user_charge  =  input ( "Do you want to charge more money?[\033[32;1my|n|b]\033[0m" ).strip()
                         if  user_charge  = =  "y"  or  user_charge  = =  "yes" :
                             charge_number  =  input ( "Please input your top-up amount:" ).strip()
                             if  charge_number.isdigit():
                                 charge_number  =  int (charge_number)
                                 money  + =  charge_number   #充值成功
                                 print ( "Your balance is [\033[32;1m%s\033[0m]"  %  money)
                             else :
                                 print ( "Your input is not number!" )
                                 continue
                             break
                         elif  user_charge  = =  "n"  or  user_charge  = =  "no"  or  user_charge  = =  "b"  or  user_charge  = =  "back" :
                             break    #放弃充值
         else :
             if  user_choice  = =  "q"  or  user_choice  = =  "quit" :
                 show_shopping_cart()
                 exit( "Bye,thanks!" .center( 50 , "#" ))
             elif  user_choice  = =  "c"  or  user_choice  = =  "check" :
                 print ( "You purchased products as below" .center( 50 , "*" ))
                 print ( "%-20s %-15s %-10s %-20s"  % ( "Goods" , "Price" , "Number" , "Cost" ))
                 for  key  in  shopping_cart:
                     p_name  =  key[ 0 ]
                     p_price  =  int (key[ 1 ])
                     p_number  =  int (shopping_cart[key])
                     print ( "%-20s %-15s %-10s \033[32;1m%-20s\033[0m"  % (p_name,p_price,p_number,p_price * p_number))
                 print ( "End" .center( 50 , "*" ))
                 print ( "%-20s %-15s %-10s \033[32;1m%-20s\033[0m"  % ( "You total cost:" ," "," ",all_cost))
                 print ( "Your balance is [\033[32;1m%s\033[0m]"  %  money)
             elif  user_choice  = =  "b"  or  user_choice  = =  "back" :
                 exit_flag  =  True
             else :
                 print ( "Your input is error!" )

 

总结:

1.用到的基础知识点不少,不仅复习了day1知识,更灵活运用了列表、字典、元组等;

2.购物车还可以再完美,比如增加商品列表固定排序(如果使用json,我不知道怎么用),增加余额充值接口(使用信用卡)等;

3.对于复杂一些的需求,层次要分明,条理清晰,才能使自己逻辑思维鲜明;



本文转自 ygqygq2 51CTO博客,原文链接:http://blog.51cto.com/ygqygq2/1865581,如需转载请自行联系原作者

相关文章
|
6月前
|
存储 JavaScript Java
(Python基础)新时代语言!一起学习Python吧!(四):dict字典和set类型;切片类型、列表生成式;map和reduce迭代器;filter过滤函数、sorted排序函数;lambda函数
dict字典 Python内置了字典:dict的支持,dict全称dictionary,在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度。 我们可以通过声明JS对象一样的方式声明dict
420 1
|
6月前
|
存储 Java 数据处理
(numpy)Python做数据处理必备框架!(一):认识numpy;从概念层面开始学习ndarray数组:形状、数组转置、数值范围、矩阵...
Numpy是什么? numpy是Python中科学计算的基础包。 它是一个Python库,提供多维数组对象、各种派生对象(例如掩码数组和矩阵)以及用于对数组进行快速操作的各种方法,包括数学、逻辑、形状操作、排序、选择、I/0 、离散傅里叶变换、基本线性代数、基本统计运算、随机模拟等等。 Numpy能做什么? numpy的部分功能如下: ndarray,一个具有矢量算术运算和复杂广播能力的快速且节省空间的多维数组 用于对整组数据进行快速运算的标准数学函数(无需编写循环)。 用于读写磁盘数据的工具以及用于操作内存映射文件的工具。 线性代数、随机数生成以及傅里叶变换功能。 用于集成由C、C++
556 1
|
6月前
|
算法 Java Docker
(Python基础)新时代语言!一起学习Python吧!(三):IF条件判断和match匹配;Python中的循环:for...in、while循环;循环操作关键字;Python函数使用方法
IF 条件判断 使用if语句,对条件进行判断 true则执行代码块缩进语句 false则不执行代码块缩进语句,如果有else 或 elif 则进入相应的规则中执行
1129 1
|
11月前
|
安全 数据安全/隐私保护 Python
Python学习的自我理解和想法(27)
本文记录了学习Python第27天的内容,主要介绍了使用Python操作PPTX和PDF的技巧。其中包括通过`python-pptx`库创建PPTX文件的详细步骤,如创建幻灯片对象、选择母版布局、编辑标题与副标题、添加文本框和图片,以及保存文件。此外,还讲解了如何利用`PyPDF2`库为PDF文件加密,涵盖安装库、定义函数、读取文件、设置密码及保存加密文件的过程。文章总结了Python在处理文档时的强大功能,并表达了对读者应用这些技能的期待。
|
6月前
|
存储 Java 索引
(Python基础)新时代语言!一起学习Python吧!(二):字符编码由来;Python字符串、字符串格式化;list集合和tuple元组区别
字符编码 我们要清楚,计算机最开始的表达都是由二进制而来 我们要想通过二进制来表示我们熟知的字符看看以下的变化 例如: 1 的二进制编码为 0000 0001 我们通过A这个字符,让其在计算机内部存储(现如今,A 字符在地址通常表示为65) 现在拿A举例: 在计算机内部 A字符,它本身表示为 65这个数,在计算机底层会转为二进制码 也意味着A字符在底层表示为 1000001 通过这样的字符表示进行转换,逐步发展为拥有127个字符的编码存储到计算机中,这个编码表也被称为ASCII编码。 但随时代变迁,ASCII编码逐渐暴露短板,全球有上百种语言,光是ASCII编码并不能够满足需求
302 4
|
7月前
|
JavaScript Java 大数据
基于python的网络课程在线学习交流系统
本研究聚焦网络课程在线学习交流系统,从社会、技术、教育三方面探讨其发展背景与意义。系统借助Java、Spring Boot、MySQL、Vue等技术实现,融合云计算、大数据与人工智能,推动教育公平与教学模式创新,具有重要理论价值与实践意义。
|
9月前
|
算法 IDE 测试技术
python学习需要注意的事项
python学习需要注意的事项
427 57
|
9月前
|
JSON 数据安全/隐私保护 数据格式
拼多多批量下单软件,拼多多无限账号下单软件,python框架仅供学习参考
完整的拼多多自动化下单框架,包含登录、搜索商品、获取商品列表、下单等功能。
|
9月前
|
机器学习/深度学习 数据安全/隐私保护 计算机视觉
过三色刷脸技术,过三色刷脸技术教程,插件过人脸python分享学习
三色刷脸技术是基于RGB三通道分离的人脸特征提取方法,通过分析人脸在不同颜色通道的特征差异

推荐镜像

更多