python-列表练习程序ver2
列表练习
1、让用户输入工资
2、输出购物菜单及产品价格
3、计算用户是否可支付
4、输出用户剩余的钱,问用户是否继续购物,如果选择继续,继续进行,只到钱不够为止
5、如若不够,提示用户剩余工资不够购买,并推出程序
--------------------------------------------------------------------------------------
1、在程序中定义列表
[email protected]:~/python# cat listshopingver3.py
#!/usr/bin/python
# --*-- coding:utf-8 --*--
products = ['Car','Iphone','Coffee','Mac','Cloths','Bicyle']
prices = [250000,4999,35,9688,438,1500]
shop_list = []
salary = int(raw_input('please input your salary:'))
while True:
print 'Thing have in the shop,please choose one to buy:'
for p in products:
#product_index = products.index(p)#产品的索引编号
print p,'\t',prices[products.index(p)]#使用产品的索引编号对应价格
choice = raw_input('Please input one item to buy:')
F_choice = choice.strip()#去掉单词中所有的空格
if F_choice in products:
product_price_index = products.index(F_choice)#产品的索引编号
product_price = prices[product_price_index]#使用产品的索引编号对应价格
print F_choice,product_price
if salary > product_price:#工资大于表示可以购买
shop_list.append(F_choice)#表示购买产品,并加入列表
print 'Added %s into your shop list'% F_choice
salary = salary - product_price#扣钱,变成新的工资
print 'Salary left:',salary#剩余工资
else:
if salary < min(prices):#min是内置函数,自动搜索列表prices的最小值
print 'Sorry,rest of your salary cannot buy anything!! bye!'
print 'you have bought these things : %s ' % shop_list
exit()
[email protected]:~/python#
--------------------------------------------------------------------------------------------------------
2、读取本目录下文件进行
[email protected]:~/python# vim listshoppingver4.py
[email protected]:~/python# ls
contact_list.txt fileinputreadfile.py listshopingver3.py oldtext.txt tab.pyc
contact_list.txt.bak fileseekblank.py listshopping.py scan1.py test.py
csvt01 fileseek.py listshoppingver4.py scanhostport.py test.txt
csvtpy fileseekstart.py manage_query.py shoppinglist.txt userinput.py
fileinputbak.py listshopingver2.py newtext.txt tab.py xwbtest.txt
[email protected]:~/python# cat listshoppingver4.py
#!/usr/bin/python
# --*-- coding:utf-8 --*--
f = file('shoppinglist.txt')
products = []
prices = []
for line in f.readlines():#把shoppinglist.txt每行循环读取出
new_line = line.split()#字符分割split必须赋值给变量才可以
products.append(new_line[0])#把shoppinglist.txt每行分割的第一列元素读取出,并存储到products列表中
prices.append(new_line[1])#把shoppinglist.txt每行分割的第二列元素读取出,并存储到products列表中
print products
print prices
[email protected]:~/python#