您的位置:首页 > 编程语言 > Python开发

【Python笔记】no.1列表的使用之超市购物示例

2017-09-14 16:48 711 查看
#代码#

#coding=utf-8

import sys

f = file('menu.txt')

products = []

prices = []

f.readline()

for line in f.readlines():

        new_line=line.split()

        products.append(new_line[0])

        prices.append(int(new_line[1]))

money = int(raw_input('请输入你的余额:'))

while True:

        print "========您好,欢迎来到华润超市,以下是商品价格清单:=========\n"

        for p in products:

                p_index = products.index(p)

                p_price = prices[p_index]

                print p,p_price

        select = raw_input('请输入商品名:')

        s = select.strip()

        #print s,s1

        if s in products:

                if money >= prices[products.index(s)]:

                        money = money-prices[products.index(s)]

                        print '您已购买成功!您的余额为:%d\n' % money

                        q = raw_input('退出请输入1,继续购买请直接回车:')

                        if q=='1':

                                sys.exit()

                        else:print '======欢迎继续购物=======\n'

                else:

                        w = raw_input('您的余额不足,请充值!充值请输入1,退出请直接回车:')

                        if w!='1':

                                sys.exit()

                        else:

                                c = int(raw_input('请输入您要充值的金额并回车:'))

                                money = money+c

                                print '您已充值成功!您的余额为%d' % money

else:

                print '不好意思,商品不存在!'

#=============================分割线==================================#

代码中调用的文件'menu.txt'位于root目录下:

root@controller:~# vi menu.txt 

Prices          pruductions

  A                100

  B                200

  C                1000

  D                2000

  E                5000

说明:

上面代码主要用到了文件处理函数、列表函数、while True循环、if else、sys模块、用户交互模块、空格过滤。

环境:ubuntu 14.04   python2.7

效果:

图一↓


 

图二↓:



图三↓:



感谢你的阅览,如你有何建议或发现笔记中有错误可向我提出,谢谢~

End.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: