一、程序功能
购物功能
-输入工资
-列出购物菜单
-选择购物项目
-选择的购物项目,金额小于工资,扣钱,加入购物车
-选择的购物项目,金额大于工资,给出提示,买金额小的项目
-此时输入quit,退出购物,列出购物清单,退出
二、流程图如下
三、python代码
#!/usr/bin/env python
import sys
salary = int(raw_input(‘Please input your salary:‘))
products = [
[‘Iphone‘,5800],
[‘MacPro‘,12000],
[‘NB Shoes‘,680],
[‘Cigarate‘,48],
[‘MX4‘,2500]
]
#create a shopping list
shopping_list = []
while True:
for p in products:
print products.index(p) ,p[0], p[1]
choice = raw_input("\033[32;1mPlease choose sth to buy:\033[0m")
if choice == ‘quit‘:
print "You have bought below stuff:"
for i in shopping_list:
print ‘\t‘,i
sys.exit(‘Goodbye!‘)
if len(choice) == 0:continue
if not choice.isdigit():continue
choice = int(choice)
if choice >= len(products):
print ‘\033[31;1m Could not find this item\033[0m‘
continue
pro = products[choice]
if salary >= pro[1]: #means you can afford this
salary = salary - pro[1]
shopping_list.append(pro)
print "\033[34;1mAdding %s to shopping list, you have %s left\033[0m" % (pro[0], salary)
else:
print ‘The price of %s is %s, yet your current balance is %s,so try another one!‘ %(pro[0],pro[1], salary)
四、运行演示
[root@s01-ansible-106-k3 Day2]# python shopping.py
Please input your salary:8000
0 Iphone 5800
1 MacPro 12000
2 NB Shoes 680
3 Cigarate 48
4 MX4 2500
Please choose sth to buy:0
Adding Iphone to shopping list, you have 2200 left
0 Iphone 5800
1 MacPro 12000
2 NB Shoes 680
3 Cigarate 48
4 MX4 2500
Please choose sth to buy:2
Adding NB Shoes to shopping list, you have 1520 left
0 Iphone 5800
1 MacPro 12000
2 NB Shoes 680
3 Cigarate 48
4 MX4 2500
Please choose sth to buy:2
Adding NB Shoes to shopping list, you have 840 left
0 Iphone 5800
1 MacPro 12000
2 NB Shoes 680
3 Cigarate 48
4 MX4 2500
Please choose sth to buy:3
Adding Cigarate to shopping list, you have 792 left
0 Iphone 5800
1 MacPro 12000
2 NB Shoes 680
3 Cigarate 48
4 MX4 2500
Please choose sth to buy:quit
You have bought below stuff:
[‘Iphone‘, 5800]
[‘NB Shoes‘, 680]
[‘NB Shoes‘, 680]
[‘Cigarate‘, 48]
Goodbye!
本文出自 “hanyun.fang” 博客,转载请与作者联系!
原文地址:http://hanyun.blog.51cto.com/1060170/1793346