要求:
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
执行结果
最终筛选的执行结果:
总结:
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__'
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。