要求:

    1,让用户输入有多少钱:

    2,输出用户能够买的东西

    3,把用户买的东西放在列表里

    4,计算用户还有多少钱,直到不能购买任何商品为止,

    5,用户只要选择商品,不能退换


Python 2.7版本

代码实现:

# -*- coding: utf-8 -*-

products = ["book","plane","phone","fan","hen","bed","car"]
price    = [65, 100000,10000,70,25,1250,1000000]
shop_list= []


salary = int(raw_input("please input your money:"))

while 1:
	print u'请从以下商品中挑选一个或者几个购买:'
	for i in range(0,len(products)):
		if (salary>=price[i]):
			print products[i],price[i]
	print "+---------------------------------+"
	choice  = raw_input("please choice a shop to buy:")
	F_choice = choice.strip()#去除空格,格式化输出。
	
	if F_choice in products:
		product_price = price[products.index(F_choice)] #取出产品价格
		print "+---------------------------------+"
		print u"你要购买的商品以及价格:",F_choice,product_price
		print u"商品正在加入购物列表,请稍等"
		if salary > product_price:
			shop_list.append(F_choice)
			salary = salary - product_price
			print "+---------------------------------+"
			print u"%s已经添加到你的购物列表" % F_choice
			print u"你的余额还有:", salary
			print u"你已经购买的商品有:", shop_list
			print "+---------------------------------+"
		else:
			pass
	else:
		print u"你输入的商品不在商品列表里,请重新输入!"

如果商品在文件里,可以用下面的代码进行处理成一个列表:

#-*-coding:utf-8 -*-
products=[]
prices=[]

f = file("jiage.txt")
for line in f.readlines():
        new_line = line.split()
        products.append(new_line[0])
        prices.append(int(new_line[1]))


print products
print prices

执行结果

wKioL1lrdw2yfficAAAQB_waWWA718.png


最终筛选的执行结果:

wKioL1lrStqgN1oIAAEyivhvVNk834.png-wh_50


总结:

product_price = price[products.index(F_choice)] #取出产品价格

这行代码python2.7和Python2.6貌似不大一样。

另外一种写法是:

product_price = price[products.index[F_choice]] #取出产品价格

但是会报下面的错误,下面的是我粘贴过来的:只要改成()的写法就行了。

TypeError: 'builtin_function_or_method' object has no attribute '__getitem__'


wKiom1lrSvXAkbkGAAQF1aT1ixQ204.png