浅谈自学Python之路(购物车程序练习)

购物车程序练习

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

  1. 购物车程序需要用到什么知识点
  2. 需要用到哪些循环
  3. 程序编写过程中考虑值的类型,是int型还是字符串
  4. 如果值为字符串该怎么转成int型
  5. 用户如何选择到商品并把其加入购物车内(根据索引值)
  6. 明白购物车流程:先输入自己的rmb—列出商品的名称和价格(用列表实现)—输入用户选择的商品(根据索引值)—判断你的rmb是否足以支付商品的价格—如果是则加入购物车—如果否则提示余额不足—你可以无限制的购买商品(前提是钱足够)—如果不想购买可以输入值结束循环—输出购买的商品及余额

那么以上就是这个程序的思路,由于我也是第一次写这个程序,所以如果思路上有什么错误的地方,还请大家谅解,在最后我会放上源码供大家参考,那么现在就开始一起写代码叭!!

 

  • 定义一个商品的列表
1 product_list = [
2     ('iphone',5000),
3     ('coffee',31),
4     ('bicyle',888),
5     ('iwatch',2666),
6     ('Mac Pro',12000),
7     ('book',88)
8 ]
  • 定义一个购物车列表,起初是空的,所以列表中为空
1 shopping_list = []#空列表,存放购买的商品
  • 然后是输入你的rmb
1 salary = input("请输入你的工资:")
2 if salary.isdigit():# isdigit() 方法检测字符串是否只由数字组成,是则返回True,否则返回False
3     salary = int(salary)

这里用到了isdigit()方法,在这里稍作解释:

描述

Python isdigit() 方法检测字符串是否只由数字组成。

语法

isdigit()方法语法:

str.isdigit()

参数

返回值

如果字符串只包含数字则返回 True 否则返回 False。

实例

以下实例展示了isdigit()方法的实例:

1 #!/usr/bin/python
2 
3 str = "123456";  # Only digit in this string
4 print str.isdigit();
5 
6 str = "this is string example....wow!!!";
7 print str.isdigit();

输出结果为:

True
False

也就是说,如果你的字符串输入的是数字,那么返回的是True,正如我写的代码,用if来判断,如果我的rmb是数字,那么成立,可以继续循环,这里大家应该都能理解,当然,如果不是,代码为:

1 else:
2     print("输入错误")

当然,我整体的代码是一个大的框架,先要判断我输入的rmb是否为数字,如果是,那么将其转为int类型,如果不是则输出:“输入错误”然后再将其他代码写入我的这个大的框架中,写程序要有一个大的框架,在脑子里先定了型,这样写起来比较调理

 

  • 接着是需要一个无限的循环

这个循环用到了  while True: 这样我就可以无限的去购买我心仪的物品,在其中添加一些其他的代码来丰富程序

先放一下其中的代码:

 1     while True:
 2         for index,i in enumerate(product_list):#index作为下标索引
 3             print(index,i)
 4 #enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。
 5         user_choice = input("请输入你要购买的商品:")
 6         if user_choice.isdigit():
 7             user_choice = int(user_choice)
 8             if user_choice < len(product_list) and user_choice >= 0:
 9                 product_choice = product_list[user_choice]
10                 if product_choice[1] < salary:#买得起
11                     shopping_list.append(product_choice)#买得起,就放入购物车
12                     salary -= product_choice[1]
13                     print("Add %s into your shopping_list,your balance is \033[31;1m%s\033[0m"%(product_choice,salary))
14                 else:
15                     print("\033[41;1m你的余额只剩%s啦,还买个叼啊!\033[0m"%salary)
16                     print("---------shopping list-----------")
17                     for s_index, s in enumerate(shopping_list):
18                         print(s_index, s)
19                     print("---------shopping list-----------")
20                     print("你的余额为:\033[31;1m%s\033[0m" % salary)
21             else:
22                 print("没有这个商品")
23         elif user_choice == "q":
24             print("---------shopping list-----------")
25             for s_index,s in enumerate(shopping_list):
26                 print(s_index,s)
27             print("---------shopping list-----------")
28             print("你的余额为:\033[31;1m%s\033[0m"%salary)
29             exit()
30         else:
31             print("输入错误")
View Code

 

  • 在这个无限循环中首先要将商品列表展现在我们面前
1         for index,i in enumerate(product_list):#index作为下标索引
2             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 这个网站里的一些知识点来进行学习

 

  • 接着是输入用户要购买的产品
1 user_choice = input("请输入你要购买的商品:")
2         if user_choice.isdigit():
3             user_choice = int(user_choice)

这三行很好理解,与输入rmb那块的代码段类似,第二第三行同样是将判断是否是数字,如果是,转成int型,否则   else: print("没有这个商品") ,这个很好理解,运用循环的时候,有 if 就有else,这是一个

固有的流程,我们写程序时,头脑中要有思路,有始有终

  • 接下来就是要编写我们购物的程序了
 1             if user_choice < len(product_list) and user_choice >= 0:
 2                 product_choice = product_list[user_choice]
 3                 if product_choice[1] < salary:#买得起
 4                     shopping_list.append(product_choice)#买得起,就放入购物车
 5                     salary -= product_choice[1]
 6                     print("Add %s into your shopping_list,your balance is \033[31;1m%s\033[0m"%(product_choice,salary))
 7                 else:
 8                     print("\033[41;1m你的余额只剩%s啦,还买个叼啊!\033[0m"%salary)
 9             else:
10                 print("没有这个商品")

这段代码比较长,但也相对简单,我来解释一下

1             if user_choice < len(product_list) and user_choice >= 0:
2                 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  ,这就是这段代码所表达的含义,可能表达的比较啰嗦,大神轻喷

1             else:
2                 print("没有这个商品")

那么如果这个值在范围以外,那么就输出 “没有这个商品”

1                 if product_choice[1] < salary:#买得起
2                     shopping_list.append(product_choice)#买得起,就放入购物车
3                     salary -= product_choice[1]
4                     print("Add %s into your shopping_list,your balance is \033[31;1m%s\033[0m"%(product_choice,salary))
5                 else:
6                     print("\033[41;1m你的余额只剩%s啦,还买个叼啊!\033[0m"%salary)

然后就要判断我是否买得起这件商品,首先要明白一个知识,我的商品列表中的 [(),()]第一个值是物品名称第二个值是价格,对应到计算机中就是 0 , 1  这两个索引 ,那么就进入我们的判断:

1                 if product_choice[1] < salary:#买得起
2                     shopping_list.append(product_choice)#买得起,就放入购物车
3                     salary -= product_choice[1]

 product_choice[1] 这个代表的是我所选商品的第二个值,即价格,如果小于我的rmb,说明买得起,那么用到了列表中的 append()方法:

描述

append() 方法用于在列表末尾添加新的对象。

语法

append()方法语法:

1 list.append(obj)

用这个方法,将我们所选商品加入到我们的购物车列表当中,此时,我们的购物车列表就有了第一个商品(之前购物车列表定义的是空列表)

1 salary -= product_choice[1]

然后,rmb需要减去我们购买的价格

1 print("Add %s into your shopping_list,your balance is \033[31;1m%s\033[0m"%(product_choice,salary))

然后输出:我们已经将商品加入到了购物车内,你的余额为xx 

1 \033[31;1m%s\033[0m

这个是控制高亮显示的代码,需要死记硬背,没有捷径,多写代码自然就记住了

1                 else:
2                     print("\033[41;1m你的余额只剩%s啦,还买个叼啊!\033[0m"%salary)

如果商品价格大于rmb那么就输出余额不足

1             print("---------shopping list-----------")
2                     for s_index, s in enumerate(shopping_list):
3                         print(s_index, s)
4                     print("---------shopping list-----------")
5                     print("你的余额为:\033[31;1m%s\033[0m" % salary)

余额不足之后呢,我需要输出你购物车内的商品,然后将购物车商品输出,然后再跳回继续选择商品;这个很好理解,我用 for 循环将购物车商品输出  ,以上几段代码是控制购买商品的代码,相对来说比较核心,需要仔细品味

 

  • 然后程序进入尾声
1         elif user_choice == "q":
2             print("---------shopping list-----------")
3             for s_index,s in enumerate(shopping_list):
4                 print(s_index,s)
5             print("---------shopping list-----------")
6             print("你的余额为:\033[31;1m%s\033[0m"%salary)
7             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("输入错误")
View Code

 

 

欢迎大家多多交流

  • 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

 

posted @ 2018-02-26 00:43  YMLiang  阅读(6553)  评论(2编辑  收藏  举报
levels of contents