浅谈自学Python之路(购物车程序练习)
购物车程序练习
今天我们来做一个购物车的程序联系,首先要理清思路
- 购物车程序需要用到什么知识点
- 需要用到哪些循环
- 程序编写过程中考虑值的类型,是int型还是字符串
- 如果值为字符串该怎么转成int型
- 用户如何选择到商品并把其加入购物车内(根据索引值)
- 明白购物车流程:先输入自己的rmb—列出商品的名称和价格(用列表实现)—输入用户选择的商品(根据索引值)—判断你的rmb是否足以支付商品的价格—如果是则加入购物车—如果否则提示余额不足—你可以无限制的购买商品(前提是钱足够)—如果不想购买可以输入值结束循环—输出购买的商品及余额
那么以上就是这个程序的思路,由于我也是第一次写这个程序,所以如果思路上有什么错误的地方,还请大家谅解,在最后我会放上源码供大家参考,那么现在就开始一起写代码叭!!
- 定义一个商品的列表
product_list = [
('iphone',5000),
('coffee',31),
('bicyle',888),
('iwatch',2666),
('Mac Pro',12000),
('book',88)
]
- 定义一个购物车列表,起初是空的,所以列表中为空
shopping_list = []#空列表,存放购买的商品
- 然后是输入你的rmb
salary = input("请输入你的工资:")
if salary.isdigit():# isdigit() 方法检测字符串是否只由数字组成,是则返回True,否则返回False
salary = int(salary)
这里用到了isdigit()方法,在这里稍作解释:
描述
Python isdigit() 方法检测字符串是否只由数字组成。
语法
isdigit()方法语法:
str.isdigit()
参数
无
返回值
如果字符串只包含数字则返回 True 否则返回 False。
实例
以下实例展示了isdigit()方法的实例:
#!/usr/bin/python str = ""; # Only digit in this string
print str.isdigit(); str = "this is string example....wow!!!";
print str.isdigit();
输出结果为:
True
False
也就是说,如果你的字符串输入的是数字,那么返回的是True,正如我写的代码,用if来判断,如果我的rmb是数字,那么成立,可以继续循环,这里大家应该都能理解,当然,如果不是,代码为:
else:
print("输入错误")
当然,我整体的代码是一个大的框架,先要判断我输入的rmb是否为数字,如果是,那么将其转为int类型,如果不是则输出:“输入错误”然后再将其他代码写入我的这个大的框架中,写程序要有一个大的框架,在脑子里先定了型,这样写起来比较调理
- 接着是需要一个无限的循环
这个循环用到了 while True: 这样我就可以无限的去购买我心仪的物品,在其中添加一些其他的代码来丰富程序
先放一下其中的代码:
while True:
for index,i in enumerate(product_list):#index作为下标索引
print(index,i)
#enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。
user_choice = input("请输入你要购买的商品:")
if user_choice.isdigit():
user_choice = int(user_choice)
if user_choice < len(product_list) and user_choice >= 0:
product_choice = product_list[user_choice]
if product_choice[1] < salary:#买得起
shopping_list.append(product_choice)#买得起,就放入购物车
salary -= product_choice[1]
print("Add %s into your shopping_list,your balance is \033[31;1m%s\033[0m"%(product_choice,salary))
else:
print("\033[41;1m你的余额只剩%s啦,还买个叼啊!\033[0m"%salary)
print("---------shopping list-----------")
for s_index, s in enumerate(shopping_list):
print(s_index, s)
print("---------shopping list-----------")
print("你的余额为:\033[31;1m%s\033[0m" % salary)
else:
print("没有这个商品")
elif user_choice == "q":
print("---------shopping list-----------")
for s_index,s in enumerate(shopping_list):
print(s_index,s)
print("---------shopping list-----------")
print("你的余额为:\033[31;1m%s\033[0m"%salary)
exit()
else:
print("输入错误")
- 在这个无限循环中首先要将商品列表展现在我们面前
for index,i in enumerate(product_list):#index作为下标索引
print(index,i)
这里用到了enumerate方法,在这里稍作解释:
描述
enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。
for 循环使用 enumerate
就是将列表中的值前方加上了数据下标,上面的代码输出结果为:
0 ('iphone', 5000)
1 ('coffee', 31)
2 ('bicyle', 888)
3 ('iwatch', 2666)
4 ('Mac Pro', 12000)
5 ('book', 88)
针对程序中所用到的一些对于像我一样的初学者来说,可以参考 http://www.runoob.com/python/python-tutorial.html 这个网站里的一些知识点来进行学习
- 接着是输入用户要购买的产品
user_choice = input("请输入你要购买的商品:")
if user_choice.isdigit():
user_choice = int(user_choice)
这三行很好理解,与输入rmb那块的代码段类似,第二第三行同样是将判断是否是数字,如果是,转成int型,否则 else: print("没有这个商品") ,这个很好理解,运用循环的时候,有 if 就有else,这是一个
固有的流程,我们写程序时,头脑中要有思路,有始有终
- 接下来就是要编写我们购物的程序了
if user_choice < len(product_list) and user_choice >= 0:
product_choice = product_list[user_choice]
if product_choice[1] < salary:#买得起
shopping_list.append(product_choice)#买得起,就放入购物车
salary -= product_choice[1]
print("Add %s into your shopping_list,your balance is \033[31;1m%s\033[0m"%(product_choice,salary))
else:
print("\033[41;1m你的余额只剩%s啦,还买个叼啊!\033[0m"%salary)
else:
print("没有这个商品")
这段代码比较长,但也相对简单,我来解释一下
if user_choice < len(product_list) and user_choice >= 0:
product_choice = product_list[user_choice]
首先是要判断,用户所选择的数字,是否小于商品的编号,并且大于等于0,在前面我也将每个商品所对应的索引值打印了下来,利用这个来判断我们是否选择了商品;接着定义了 product_choice 这个就是我们选择加入购物车的商品,它的值等于 product_list[user_choice] ,这段的意思是:用户输入要购买商品的编号,这个数字传给 product_list[user_choice] ,就将商品选择到了,举个栗子,譬如用户选择 user_choice 为 1 ,那么我们的 product_list[user_choice] 就变成了 product_list[1] ,这也就是我们将第二个商品选择到了,然后将这个值赋予给了 product_choice ,这就是这段代码所表达的含义,可能表达的比较啰嗦,大神轻喷
else:
print("没有这个商品")
那么如果这个值在范围以外,那么就输出 “没有这个商品”
if product_choice[1] < salary:#买得起
shopping_list.append(product_choice)#买得起,就放入购物车
salary -= product_choice[1]
print("Add %s into your shopping_list,your balance is \033[31;1m%s\033[0m"%(product_choice,salary))
else:
print("\033[41;1m你的余额只剩%s啦,还买个叼啊!\033[0m"%salary)
然后就要判断我是否买得起这件商品,首先要明白一个知识,我的商品列表中的 [(),()]第一个值是物品名称第二个值是价格,对应到计算机中就是 0 , 1 这两个索引 ,那么就进入我们的判断:
if product_choice[1] < salary:#买得起
shopping_list.append(product_choice)#买得起,就放入购物车
salary -= product_choice[1]
product_choice[1] 这个代表的是我所选商品的第二个值,即价格,如果小于我的rmb,说明买得起,那么用到了列表中的 append()方法:
描述
append() 方法用于在列表末尾添加新的对象。
语法
append()方法语法:
list.append(obj)
用这个方法,将我们所选商品加入到我们的购物车列表当中,此时,我们的购物车列表就有了第一个商品(之前购物车列表定义的是空列表)
salary -= product_choice[1]
然后,rmb需要减去我们购买的价格
print("Add %s into your shopping_list,your balance is \033[31;1m%s\033[0m"%(product_choice,salary))
然后输出:我们已经将商品加入到了购物车内,你的余额为xx
\033[31;1m%s\033[0m
这个是控制高亮显示的代码,需要死记硬背,没有捷径,多写代码自然就记住了
else:
print("\033[41;1m你的余额只剩%s啦,还买个叼啊!\033[0m"%salary)
如果商品价格大于rmb那么就输出余额不足
print("---------shopping list-----------")
for s_index, s in enumerate(shopping_list):
print(s_index, s)
print("---------shopping list-----------")
print("你的余额为:\033[31;1m%s\033[0m" % salary)
余额不足之后呢,我需要输出你购物车内的商品,然后将购物车商品输出,然后再跳回继续选择商品;这个很好理解,我用 for 循环将购物车商品输出 ,以上几段代码是控制购买商品的代码,相对来说比较核心,需要仔细品味
- 然后程序进入尾声
elif user_choice == "q":
print("---------shopping list-----------")
for s_index,s in enumerate(shopping_list):
print(s_index,s)
print("---------shopping list-----------")
print("你的余额为:\033[31;1m%s\033[0m"%salary)
exit()
这个代码段是建立在 用户选择 if user_choice.isdigit(): 这个基础上的, 也就是 user_choice = input("请输入你要购买的商品:") 我输入了商品前的编号, 然后进入购买商品的循环, 如果我们觉得够了,不想再买了,选择 “ q ” 然后就可以打印购买商品,各回各家各找各妈了~!
- 那么到这里这个程序就算完成了,下面附上源码,大家在看的时候务必要看清楚各各循环对应的功能,多加练习哦!
#!/usr/bin/env.python
# -*- coding: utf-8 -*-
"""
-------------------------------------------------
File Name: shopping
Description :
Author : lym
date: 2018/2/24
-------------------------------------------------
Change Activity:
2018/2/24:
-------------------------------------------------
"""
__author__ = 'lym'
#定义一个商品列表,里面写入商品的值和价格
product_list = [
('iphone',5000),
('coffee',31),
('bicyle',888),
('iwatch',2666),
('Mac Pro',12000),
('book',88)
]
shopping_list = []#空列表,存放购买的商品 salary = input("请输入你的工资:")
if salary.isdigit():# isdigit() 方法检测字符串是否只由数字组成,是则返回True,否则返回False
salary = int(salary)
while True:
for index,i in enumerate(product_list):#index作为下标索引
print(index,i)
#enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。
user_choice = input("请输入你要购买的商品:")
if user_choice.isdigit():
user_choice = int(user_choice)
if user_choice < len(product_list) and user_choice >= 0:
product_choice = product_list[user_choice]
if product_choice[1] < salary:#买得起
shopping_list.append(product_choice)#买得起,就放入购物车
salary -= product_choice[1]
print("Add %s into your shopping_list,your balance is \033[31;1m%s\033[0m"%(product_choice,salary))
else:
print("\033[41;1m你的余额只剩%s啦,还买个叼啊!\033[0m"%salary)
print("---------shopping list-----------")
for s_index, s in enumerate(shopping_list):
print(s_index, s)
print("---------shopping list-----------")
print("你的余额为:\033[31;1m%s\033[0m" % salary)
else:
print("没有这个商品")
elif user_choice == "q":
print("---------shopping list-----------")
for s_index,s in enumerate(shopping_list):
print(s_index,s)
print("---------shopping list-----------")
print("你的余额为:\033[31;1m%s\033[0m"%salary)
exit()
else:
print("输入错误")
else:
print("输入错误")
欢迎大家多多交流
- QQ:616581760
- weibo:https://weibo.com/3010316791/profile?rightmod=1&wvr=6&mod=personinfo
- zcool:http://www.zcool.com.cn/u/16265217
- huke:https://huke88.com/teacher/17655.html
浅谈自学Python之路(购物车程序练习)的更多相关文章
- 浅谈自学Python之路(day2)
今天的主要内容是: 标准库 数据类型知识 数据运算 三元运算 bytes类型 字符串操作 字典 集合 标准库 Python的强大之处在于他有非常丰富和强大的标准库和第三方库,几乎你想实现的任何功能都有 ...
- 浅谈自学Python之路(day3)
今天的主要内容是: 撒 文件操作 对文件操作的流程: 打开文件,得到文件句柄并赋值给一个变量 通过句柄对文件进行操作 关闭文件 现有文件如下: tonghuazhen 听说白雪公主在逃跑 小红帽在担心 ...
- 浅谈自学Python之路(day1)
2018-02-19 17:15:14 Python语言相对于其他语言较为简洁,也相对好入门比如后面不加分号,基本见不着大括号等优点 第一个程序,也是学每门语言都需要掌握的第一个代码 print(& ...
- NO.3:自学python之路------集合、文件操作、函数
引言 本来计划每周完成一篇Python的自学博客,由于上一篇到这一篇遇到了过年.开学等杂事,导致托更到现在.现在又是一个新的学期,春天也越来越近了(冷到感冒).好了,闲话就说这么多.开始本周的自学Py ...
- 自学Python之路
自学Python之路[第一回]:初识Python 1.1 自学Python1.1-简介 1.2 自学Python1.2-环境的搭建:Pycharm及python安装详细教程 1.3 ...
- 自学Python之路-Python核心编程
自学Python之路-Python核心编程 自学Python之路[第六回]:Python模块 6.1 自学Python6.1-模块简介 6.2 自学Python6.2-类.模块.包 ...
- 自学Python之路-Python基础+模块+面向对象+函数
自学Python之路-Python基础+模块+面向对象+函数 自学Python之路[第一回]:初识Python 1.1 自学Python1.1-简介 1.2 自学Python1.2-环境的 ...
- 自学Python之路-django
自学Python之路-django 自学Python之路[第一回]:1.11.2 1.3
- 自学Python之路-Python并发编程+数据库+前端
自学Python之路-Python并发编程+数据库+前端 自学Python之路[第一回]:1.11.2 1.3
随机推荐
- C# 控件调整
//最大化 this.WindowState = FormWindowState.Maximized; //去掉标题栏 this.FormBorderStyle = FormBorderStyle.N ...
- VMware虚拟机下Ubuntu安装VMware Tools详解
一.安装步骤 1.开启虚拟机,运行想要安装VMware Tools的系统,运行进入系统后,点击虚拟机上方菜单栏的“虚拟机(M)”->点击“安装 VMware Tools”,图片所示是因为我已经安 ...
- 洛谷——P3205 [HNOI2010]合唱队
P3205 [HNOI2010]合唱队 题目描述 为了在即将到来的晚会上有更好的演出效果,作为AAA合唱队负责人的小A需要将合唱队的人根据他们的身高排出一个队形.假定合唱队一共N个人,第i个人的身高为 ...
- Swoole 源码分析——Server模块之TaskWorker事件循环
swManager_start 创建进程流程 task_worker 进程的创建可以分为三个步骤:swServer_create_task_worker 申请所需的内存.swTaskWorker_in ...
- “从客户端(content="XXXX")中检测到有潜在危险的 Request.Form值” 解决方案
解决方案一: 在.aspx文件头中加: <%@Page validateRequest="false" %> 解决方案二: 修改web.config文件: <co ...
- 清北学堂模拟赛d4t1 a
分析:大模拟,没什么好说的.我在考场上犯了一个超级低级的错误:while (scanf("%s",s + 1)),导致了死循环,血的教训啊,以后要记住了. /* 1.没有发生改变, ...
- [poj1698]Alice's Chance[网络流]
[转]原文:http://blog.csdn.net/wangjian8006/article/details/7926040 题目大意:爱丽丝要拍电影,有n部电影,规定爱丽丝每部电影在每个礼拜只有固 ...
- SIM900A 发送AT+CSTT 总是 返回Error的原因分析
检查 模块的供电是否正常 本例 修改供电后 联网恢复正常.
- nyoj_114_某种序列_201403161700
某种序列 时间限制:3000 ms | 内存限制:65535 KB 难度:4 描述 数列A满足An = An-1 + An-2 + An-3, n >= 3 编写程序,给定A0, A1 ...
- 淘宝信海龙 --PHP系统
https://yq.aliyun.com/users/1467229535950742?spm=5176.100239.blogrightarea56002.3.RoToxZ