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,如需转载请自行联系原作者

相关文章
|
4天前
|
小程序 程序员 开发者
Python学习心得——小白的成长之路
Python学习心得——小白的成长之路
11 0
|
4天前
|
网络安全 Python
网安之python基础学习练习(2-3)
本篇博文是关于网络安全课程中Python编程的学习实践总结。分享关于两个练习题目及其解决方案。第一个题目要求用户输入姓名并选择一项武技,使用for循环和if判断实现。第二个题目是删除列表中特定值(如&#39;cat&#39;)的所有元素,作者展示了两种方法,包括列表推导式和常规循环删除。接下来,文章还介绍了如何编写一个函数,随机生成一副扑克牌(除大小王),并返回一张随机抽取的牌。
|
4天前
|
存储 网络安全 索引
网安之python基础学习练习(1)
本篇博文是关于网络安全课程中Python编程学习的总结,主要内容包括:1) 常见数据类型的回顾和应用,如数字(整数、浮点数、复数)、字符串、列表、元组、集合、字典和布尔类型;2) 数据类型的实例操作,展示如何创建和使用这些类型;3) 数值类型之间的加、减、乘、除和模运算;4) 列表和元组的索引访问;5) 字典的修改,如查看键和值,以及更新值。文章强调了基础知识的重要性,并以“自满必定失败,骄傲必定后悔”作为每日一言。
|
6天前
|
机器学习/深度学习 数据挖掘 程序员
Python学习难度的具体标准
Python学习难度因个人编程背景、目标、资源和学习能力而异。对有编程经验者来说,Python的简单语法使其易上手;而对于新手,理解基础概念可能需更多时间。不同应用领域(如Web开发、数据分析)的学习曲线也不同。丰富的学习资源适应各种水平,但选择合适资源很重要。成功学习Python需要逻辑思维、问题解决能力及毅力。总的来说,Python学习难度因人而异,需结合自身条件评估。
19 0
|
6天前
|
存储 索引 Python
python数据结构知识学习
【5月更文挑战第6天】Python提供四种核心数据结构:列表(List)——可变有序集合,支持索引和切片;元组(Tuple)——不可变有序集合;字典(Dictionary)——键值对结构,通过键访问值;集合(Set)——无序不重复元素集合,支持数学运算。此外,Python允许自定义数据结构,如链表、树、图,以适应不同问题需求。
17 0
|
12天前
|
机器学习/深度学习 分布式计算 物联网
【Python机器学习专栏】联邦学习:保护隐私的机器学习新趋势
【4月更文挑战第30天】联邦学习是保障数据隐私的分布式机器学习方法,允许设备在本地训练数据并仅共享模型,保护用户隐私。其优势包括数据隐私、分布式计算和模型泛化。应用于医疗、金融和物联网等领域,未来将发展更高效的数据隐私保护、提升可解释性和可靠性的,并与其他技术融合,为机器学习带来新机遇。
|
12天前
|
机器学习/深度学习 自然语言处理 搜索推荐
【Python机器学习专栏】迁移学习在机器学习中的应用
【4月更文挑战第30天】迁移学习是利用已有知识解决新问题的机器学习方法,尤其在数据稀缺或资源有限时展现优势。本文介绍了迁移学习的基本概念,包括源域和目标域,并探讨了其在图像识别、自然语言处理和推荐系统的应用。在Python中,可使用Keras或TensorFlow实现迁移学习,如示例所示,通过预训练的VGG16模型进行图像识别。迁移学习提高了学习效率和性能,随着技术发展,其应用前景广阔。
|
12天前
|
机器学习/深度学习 算法 前端开发
【Python机器学习专栏】集成学习中的Bagging与Boosting
【4月更文挑战第30天】本文介绍了集成学习中的两种主要策略:Bagging和Boosting。Bagging通过自助采样构建多个基学习器并以投票或平均法集成,降低模型方差,增强稳定性。在Python中可使用`BaggingClassifier`实现。而Boosting是串行学习,不断调整基学习器权重以优化拟合,适合弱学习器。Python中可利用`AdaBoostClassifier`等实现。示例代码展示了如何在实践中运用这两种方法。
|
12天前
|
机器学习/深度学习 算法 数据挖掘
【Python机器学习专栏】关联规则学习:Apriori算法详解
【4月更文挑战第30天】Apriori算法是一种用于关联规则学习的经典算法,尤其适用于购物篮分析,以发现商品间的购买关联。该算法基于支持度和置信度指标,通过迭代生成频繁项集并提取满足阈值的规则。Python中可借助mlxtend库实现Apriori,例如处理购物篮数据,设置支持度和置信度阈值,找出相关规则。
|
12天前
|
机器学习/深度学习 算法 前端开发
【Python机器学习专栏】集成学习算法的原理与应用
【4月更文挑战第30天】集成学习通过组合多个基学习器提升预测准确性,广泛应用于分类、回归等问题。主要步骤包括生成基学习器、训练和结合预测结果。算法类型有Bagging(如随机森林)、Boosting(如AdaBoost)和Stacking。Python中可使用scikit-learn实现,如示例代码展示的随机森林分类。集成学习能降低模型方差,缓解过拟合,提高预测性能。