一、程序功能
購物功能
-輸入工資
-列出購物菜單
-選擇購物項目
-選擇的購物項目,金額小於工資,扣錢,加入購物車
-選擇的購物項目,金額大於工資,給出提示,買金額小的項目
-此時輸入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!