python-购物车程序

2021/5/13 1:26:02

本文主要是介绍python-购物车程序,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

需求:

启动程序后,让用户输入工资,然后打印商品列表

允许用户根据商品编号购买商品

用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒

用户可一直购买商品,也可随时退出,退出打印已购商品和余额


解答:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:young
shopping_list = [
    ('Watch',1200),
    ('PC',11100),
    ('Iphone',7800),
    ('Bag',230)
]
shopped_list = []         #空列表,存放购买商品
salary = input('请输入你的工资:')
if salary.isdigit():      #判断输入的工资是否是数字
    salary = int(salary)  #转
    while True:
        for index,shop in enumerate(shopping_list):
            print(index,shop)
        user_choice = input("请输入商品编码:")
        if user_choice.isdigit():
            user_choice = int(user_choice)
            if user_choice >= 0 and user_choice < len(shopping_list):
                if salary >= shopping_list[user_choice][1]:
                    shopped_list.append(shopping_list[user_choice])
                    salary = salary - shopping_list[user_choice][1]
                else:
                    print('你的钱不够购买此商品,请更换其他商品,或者按q退出购买')
            else:
                print('你输入的商品编号不存在!')
        elif user_choice == 'q':
            print('你购买了%s商品,还剩下%s的钱'% (shopped_list,salary))
            exit()
        else:
            print('输入的商品编号必须是数字!')
else:
        print('你输入薪水有误,必须是数字才行哟!')


这篇关于python-购物车程序的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程