码迷,mamicode.com
首页 > 其他好文 > 详细

实例 - 购物车 (列表、循环)

时间:2018-02-22 21:25:35      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:小结   inpu   数据   索引   print   遍历   star   coff   tar   

 

salary = int(input(Please input your money:))

product = [
    (iphone6s,5800),
    (mac bood,9000),
    (coffee,32),
    (python book,80),
    (bicyle,1500),
]

shopping = []

while True:
    #打印商品内容
    n = 1
    for i,v in product:
        print(n,.,i,v)
        n += 1
    #引导用户选择商品
    choice = input(选择购买商品编号:<退出:q>)

    #验证输入是否符合规范
    if choice.isdigit():
        choice = int(choice)
        if choice > 0 and choice <= len(product):
            #判断存款是否大于余额
            if salary > product[choice-1][1]:
                #计算余额,并将商品加入购物列表,并提示用户购买成功
                salary = salary - product[choice-1][1]
                shopping.append(product[choice-1][0])
                print(已加入%s到您的购物车,当前余额为:%s%(product[choice-1][0],salary))
            else:
                print(余额不足,你的余额为:%d%salary)
        else:
            print(编码不存在)
    #验证用户是否退出,并将购物车中内容打印
    elif choice == q:
        print(-*10,您已经购买如下商品,-*10)
        for u in shopping:
            print(u)
        print(你的余额为:%d%salary)
        break
    else:
        print(invalid input)

实例小结:

 

.isdigit() 

  描述:检测字符串是否只由数字组成 

  语法:str.isdigit()

  返回值:如果字符串只包含数字则返回 True 否则返回 False

enumerate()

  描述:enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中

  语法:enumerate(sequence, [start=0])

  参数:sequence -- 一个序列、迭代器或其他支持迭代对象

     start -- 下标起始位置

  返回值:返回 enumerate(枚举) 对象

  实例:

seasons = [Spring, Summer, Fall, Winter]

res1 = list(enumerate(seasons))

res2 = list(enumerate(seasons,1))

print(res1)

print(res2)
技术分享图片
[(0, Spring), (1, Summer), (2, Fall), (3, Winter)]
[(1, Spring), (2, Summer), (3, Fall), (4, Winter)]
Run result

  for 循环使用 enumerate:

seq = [one, two, three]
for i, element in enumerate(seq):
    print (i, seq[i])
技术分享图片
0 one
1 two
2 three
Run result

 

实例 - 购物车 (列表、循环)

标签:小结   inpu   数据   索引   print   遍历   star   coff   tar   

原文地址:https://www.cnblogs.com/id19910408/p/8459860.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!