让用户输入工资
输出购物菜单及产品价格
计算用户是否可支付
输出用户剩余的钱,问用户是否继续购物,如果选择继续,继续进行,直到钱不够为止
#coding:UTF-8
import sys
while True:
try:
salary = int(raw_input(‘Please input your salary:‘).strip())
break
except:
print ‘Please input a valid number‘
continue #Ctrl-C不能退出
f_file = ‘shop_list.txt‘
f = file(f_file)
shop_list = {}
for line in f.readlines():
line = line.split()
line[1] = int(line[1]) #从文件读进来的的字符串,没法比较
shop_list[line[0]] = line[1]
f.close()
customer_shop_list = [] #用字典的话,用户买相同产品时,输出最终购买商品不能输出重复的,可以做成*2这种样式解决
while True:
for k,v in shop_list.items():
print k,v
if min(shop_list.values()) <= salary:
product = raw_input(‘please input what you want:‘).strip()
if product not in shop_list.keys():
print ‘Please input a valid product‘
continue
if shop_list[product] > salary:
print ‘you salary is ‘,salary
print ‘you not have too much money,Please choose again‘
continue
else:
customer_shop_list.append(product)
salary = salary - shop_list[product]
print ‘now you have:‘
for i in customer_shop_list:
print i,‘ ‘,shop_list[i]
print ‘your salary is %s now‘ %salary
continue
else:
print ‘you not have enough money‘
print ‘now you have:‘
for i in customer_shop_list:
print i,‘ ‘,shop_list[i]
print ‘your salary is %s now‘ %salary
sys.exit()原文:http://8588103.blog.51cto.com/8578103/1664113