文件结构:
原文数据:
products.db
linux 3980
python 6000
mysql 5000
oracle 10000
具体要求:
1.要求用户输入工资,然后打印购物菜单
2.用户可以不断的购买商品,直到钱不够为止
3.退出时格式化打印自己已经购买的商品和剩余金额
代码流程:
代码实现:
# -*- coding: utf-8 -*-
"""
#
# Authors: limanman
# OsChina: http://my.oschina.net/pydevops/
# Purpose:
#
1.要求用户输入工资,然后打印购物菜单
2.用户可以不断的购买商品,直到钱不够为止
3.退出时格式化打印自己已经购买的商品和剩余金额
"""
import sys
import linecache
import blessings
def main():
"""Main function."""
product_db = 'products.db'
# 输入工资
salary = input('please input your salary: ')
if isinstance(salary, (int, float, long)):
salary = round(float(salary), 2)
else:
sys.exit('Found Errors: error with your salary input!')
# 获取行列表,定义输出格式
product_lines = linecache.getlines(product_db)
total_width = int(TERMINAL.width) - 2
index_width = 10
price_width = 10
items_width = total_width - index_width - price_width
item_format = '%-*s%-*s%*s'
# 循环购买商品
shop_list = []
while True:
shop_dict = {}
# 打印表头
print '=' * total_width
print item_format % (index_width, 'INDEX',
items_width, 'ITEMS',
price_width, 'PRICE')
print '=' * total_width
# 格式化输出,并且更新商品字典
for cur_index, cur_line in enumerate(product_lines, start=0):
cur_line = cur_line.strip()
product_item = cur_line.split()[0]
product_price = float(cur_line.split()[1])
shop_dict.update({
cur_index: [product_item, product_price]
})
print item_format % (index_width, cur_index,
items_width, product_item,
price_width, product_price)
# 选择购买
cur_choice = raw_input('please input your choice: ')
# 退出结算
if cur_choice in ['quit', 'exit']:
print 'your shopping cart: '
print '=' * total_width
print item_format % (index_width, 'INDEX',
items_width, 'ITEMS',
price_width, 'PRICE')
print '=' * total_width
for cur_item in shop_list:
print item_format % (index_width, cur_item[0],
items_width, cur_item[1],
price_width, cur_item[2],)
print '-' * total_width
total_money = sum(zip(shop_list[0],
shop_list[1], shop_list[2])[-1])
print item_format % (index_width, 'Total',
items_width, ' ',
price_width, total_money)
break
# 购买扣钱
if cur_choice.isdigit():
cur_choice = int(cur_choice)
else:
print 'Found Errors: error with your choice input!'
salary -= shop_dict[cur_choice][-1]
# 没钱退出
if salary <= 0:
print 'Found Notice: you have not enough money!'
break
# 否则加入购物车
shop_list.append([
cur_choice,
shop_dict[cur_choice][0],
shop_dict[cur_choice][1],
])
print ','.join([
'Found Notice: you purchase %s' % (shop_dict[cur_choice][0]),
'cost %s money' % (shop_dict[cur_choice][-1]),
'your balance is %s' % (salary)
])
# 更新商品数据库
linecache.updatecache(product_db)
if __name__ == '__main__':
TERMINAL = blessings.Terminal()
main()