购物车程序练习

今天我们来做一个购物车的程序联系,首先要理清思路

  1. 购物车程序需要用到什么知识点
  2. 需要用到哪些循环
  3. 程序编写过程中考虑值的类型,是int型还是字符串
  4. 如果值为字符串该怎么转成int型
  5. 用户如何选择到商品并把其加入购物车内(根据索引值)
  6. 明白购物车流程:先输入自己的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之路(购物车程序练习)的更多相关文章

  1. 浅谈自学Python之路(day2)

    今天的主要内容是: 标准库 数据类型知识 数据运算 三元运算 bytes类型 字符串操作 字典 集合 标准库 Python的强大之处在于他有非常丰富和强大的标准库和第三方库,几乎你想实现的任何功能都有 ...

  2. 浅谈自学Python之路(day3)

    今天的主要内容是: 撒 文件操作 对文件操作的流程: 打开文件,得到文件句柄并赋值给一个变量 通过句柄对文件进行操作 关闭文件 现有文件如下: tonghuazhen 听说白雪公主在逃跑 小红帽在担心 ...

  3. 浅谈自学Python之路(day1)

    2018-02-19  17:15:14 Python语言相对于其他语言较为简洁,也相对好入门比如后面不加分号,基本见不着大括号等优点 第一个程序,也是学每门语言都需要掌握的第一个代码 print(& ...

  4. NO.3:自学python之路------集合、文件操作、函数

    引言 本来计划每周完成一篇Python的自学博客,由于上一篇到这一篇遇到了过年.开学等杂事,导致托更到现在.现在又是一个新的学期,春天也越来越近了(冷到感冒).好了,闲话就说这么多.开始本周的自学Py ...

  5. 自学Python之路

    自学Python之路[第一回]:初识Python    1.1 自学Python1.1-简介    1.2 自学Python1.2-环境的搭建:Pycharm及python安装详细教程    1.3  ...

  6. 自学Python之路-Python核心编程

    自学Python之路-Python核心编程 自学Python之路[第六回]:Python模块       6.1 自学Python6.1-模块简介    6.2 自学Python6.2-类.模块.包  ...

  7. 自学Python之路-Python基础+模块+面向对象+函数

    自学Python之路-Python基础+模块+面向对象+函数 自学Python之路[第一回]:初识Python    1.1 自学Python1.1-简介    1.2 自学Python1.2-环境的 ...

  8. 自学Python之路-django

    自学Python之路-django 自学Python之路[第一回]:1.11.2 1.3

  9. 自学Python之路-Python并发编程+数据库+前端

    自学Python之路-Python并发编程+数据库+前端 自学Python之路[第一回]:1.11.2 1.3

随机推荐

  1. NGINX+PHP-FPM7 FastCGI sent in stderr: “Primary script unknown”

    https://www.cnblogs.com/hjqjk/p/5651275.html 一开始是Nginx打开网页显示一直是拒绝访问.查看nginx日志是报错显示我的题目,然后就各种搜索解决啊! 百 ...

  2. linux下如何限制普通用户更改密码

    问题描述: 为了方便linux管理员对所有用户的进行管理,如何限制普通用户更改密码? 解决方法: 禁止普通用户更改密码: /usr/bin/passwd 若要允许普通用户更改密码: /usr/bin/ ...

  3. mysql cpu 100% 满 优化方案 解决MySQL CPU占用100%的经验总结

    下面是一些经验 供参考 解决MySQL CPU占用100%的经验总结 - karl_han的专栏 - CSDN博客 https://blog.csdn.net/karl_han/article/det ...

  4. HTML学习笔记之标签基础

    目录 1.基本标签 2.链接 3.图像 4.表格 5.列表 6.块与布局 1.基本标签 (1)标题与段落 标签 <h1> ~ <h6> 分别用于定义一至六级标题,标签 < ...

  5. django的时间问题

    三个时间datetime.datetime.now().datetime.datetime.utcnow()与django.util.timezone.now()的区别 datetime.dateti ...

  6. 洛谷 2147 SDOI2008 Cave 洞穴勘测

    [题解] 动态树模板题,只要求维护森林的连通性,直接上板子即可. #include<cstdio> #include<algorithm> #define N 500010 # ...

  7. 【Codeforces 225C】Barcode

    [链接] 我是链接,点我呀:) [题意] 让你把每一列都染成一样的颜色 要求连续相同颜色的列的长度都大于等于x小于等于y 问你最少的染色次数 [题解] 先求出每一列染成#或者.需要染色多少次 设f[0 ...

  8. springboot优雅关机

    Spring boot 2.0 之优雅停机  rabbitGYK 关注 2018.05.20 18:41* 字数 1794 阅读 2638评论 0喜欢 22 spring boot 框架在生产环境使用 ...

  9. hdu_1048_The Hardest Problem Ever_201311052052

    The Hardest Problem Ever Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java ...

  10. POJ 3061 Subsequence 尺取

    Subsequence Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 14698   Accepted: 6205 Desc ...