列表练习
1、让用户输入工资
2、输出购物菜单及产品价格
3、计算用户是否可支付
4、输出用户剩余的钱,问用户是否继续购物,如果选择继续,继续进行,只到钱不够为止
5、如若不够,提示用户剩余工资不够购买,并推出程序
--------------------------------------------------------------------------------------
1、代码如下
#!/usr/bin/python
# --*-- coding:utf-8 --*--
f = file('shoppinglist.txt')
products = []
prices = []
shoplist = []#购买成功的产品
for line in f.readlines():#把shoppinglist.txt每行循环读取出
new_line = line.split()#字符分割split必须赋值给变量才可以
products.append(new_line[0])#把shoppinglist.txt每行分割的第一列元素读取出,并存储到products列表中
prices.append(int(new_line[1]))#把shoppinglist.txt每行分割的第二列元素读取出,并存储到products列表中,强制转换int类型
print products
print prices
salary = int(raw_input('please input your salary:'))
while True:
print 'Welcome, thing you can buy as below:'
for p in products:#打印所有可以购买的产品
p_index = products.index(p)#读取每个产品的编号
p_price = prices[p_index]#读取每个产品编号对应的价格
print p,p_index,p_price
choice = raw_input('please input what you want to buy:')
f_choice = choice.strip()#去掉输入整个字符前的与/或后所有空格
if f_choice in products:#如果产品在购物清单中则显示如下信息
print 'yes , it is in the list'
f_index = products.index(f_choice)#找到输入的产品在products中的位置
f_price = prices[f_index]#找出输入的产品在prices中价格的位置
print f_price,type(f_price)
if salary >= f_price:#在此处比较必须是同一类型数据才能比较,所以在prices列表中数据强制转换成int
print 'congratulations !added %s to list ' % f_choice
shoplist.append(f_choice)#把成功购买的产品加入列表中
salary = salary - f_price#减去购买产品的价钱
print 'Now you have %d left! keep buying!'% salary
else:#输入的产品无法购买,请选择如下产品
if salary < min(prices):#买不起最小价格的产品
print 'you can not buy anthing, BYe!'
print 'you have bought : ',shoplist
exit()
else:
print 'i am sorry, money is not enough to buy %s ,please try anthor one!'% f_choice
else:#选择的产品不在列表中
print 'i am sorry ! %s not in the list,try again'% f_choice
2、实操
root@kali:~/python# vim listshoppingver4.py
root@kali:~/python# python listshoppingver4.py
['Car', 'Iphone', 'Coffee', 'Bicyle', 'Book']
[250000, 7999, 35, 1500, 50]
please input your salary:8054
Welcome, thing you can buy as below:
Car 0 250000
Iphone 1 7999
Coffee 2 35
Bicyle 3 1500
Book 4 50
please input what you want to buy:Iphone
yes , it is in the list
7999 <type 'int'>
congratulations !added Iphone to list
Now you have 55 left! keep buying!
Welcome, thing you can buy as below:
Car 0 250000
Iphone 1 7999
Coffee 2 35
Bicyle 3 1500
Book 4 50
please input what you want to buy:Book
yes , it is in the list
50 <type 'int'>
congratulations !added Book to list
Now you have 5 left! keep buying!
Welcome, thing you can buy as below:
Car 0 250000
Iphone 1 7999
Coffee 2 35
Bicyle 3 1500
Book 4 50
please input what you want to buy:Car
yes , it is in the list
250000 <type 'int'>
you can not buy anthing, BYe!
you have bought : ['Iphone', 'Book']
root@kali:~/python# vim listshoppingver4.py
root@kali:~/python#