程序:
让用户输入薪资
输出商品及商品价格
计算用户能否支付
输出剩余的钱,问用户是否继续购物,直到钱不够为止
调用shop.txt文件内容:
[root@localhost py]# cat shop.txt mac 10000 iphone 5000 tea 400 coffee 35 boots 999
#!/usr/bin/env python #coding=utf-8 import sys f=file(‘shop.txt‘) products = [] prices = [] shop_list = [] shop_count = [] #存储购买物品,计算同一物品购买数量 for line in f.readlines(): new_line = line.split() #通过指定分隔符对字符串进行切片 products.append(new_line[0]) prices.append(int(new_line[1])) #默认str类型 salary = int(raw_input(‘请输入你的工资:‘)) while True: print "~~~~~~~~~~~~~~~~~商品列表:~~~~~~~~~~~~~~~~~" for p in products: print p,‘\t‘,prices[products.index(p)] choice = raw_input(‘请选择你购买的商品:‘) f_choice = choice.strip() #移除字符串头尾指定的字符(默认为空格) if f_choice in products: price = prices[products.index(f_choice)] if salary >= price: shop_list.append(f_choice) print f_choice,price,"已经添加到购物车中。" salary = salary - price print "您的余额:" ,salary if f_choice not in shop_count: shop_count.append(f_choice) else: if salary < min(prices): print"余额不足。一共买了这些商品:" for p in shop_count: print "%s\t*%d"%(p,shop_list.count(p)) sys.exit() #程序退出 else:print "对不起,您的余额:%d。请购买其他商品" %salary else:print"选择不在商品列表中。"
本文出自 “凌风” 博客,请务必保留此出处http://fgf01.blog.51cto.com/3907069/1718997
原文:http://fgf01.blog.51cto.com/3907069/1718997