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

 

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

 

转载于:https://www.cnblogs.com/id19910408/p/8459860.html

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值