购物车程序

2017-09-15  22:09:11


"""本代码实现的功能:
    1、启动程序,输入用户名和密码,若匹配成功,则进行下一次操作,否则继续输入用户名密码;
    2、显示查看购物车还是购买商品,然后让用户输入工资,再然后打印商品列表;
    3、允许用户根据商品编号购买商品;
    4、用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒;
    5、可随时退出,退出时,打印已购买的商品和余额,并把商品写入到文件中。
"""

# -*- coding:utf-8 -*-
# author:Mr.chan

import sys

def login(username,password):
    """用户登录函数,判断用户名和密码是否正确"""
    with open("userlist.txt", 'r',encoding='utf-8') as f:
        for line in f:
            if [username, password] == line.strip().split('|')[0:2]:  # 判断用户名和密码是否正确
                return True   # 若用户名和密码匹配成功,则返回True

def show_product_list():
    """展示商品列表 product_list """
    for index,item in enumerate(product_list):
        item_name = item[0]
        item_price = item[1]
        print("{0} >>> {1} {2}".format(index,item_name,item_price))

def show_purchased():
    """显示购物车列表 shopping_cart(因为未结算,所以不在文件中查询已购买商品)"""
    print("Purchased products:".center(30, '-'))
    for k,v in shopping_cart:
        con = k +'|'+ v
        print(con)
    print("Your balance is %s
" % salary)

product_list = [
    ('TCL TV','3500'),
    ('Android phone','3000'),
    ('Iphone 8','8000'),
    ('Lenovo computer','4000'),
    ("Haier refrigerator",'1500')
]

def salary_isdigit():
    """判断输入的薪资是否是数字"""
    global salary  # 因为其他函数需要调用salar,所以不得不在这里定义为全局变量
    while True:
        salary = input("
Input your salary:")
        if salary.isdigit():
            salary = int(salary)
            break
        else:
            print("33[31;1mIncorrect input33[0m
")

def shopping_list():
    """把购物车中的商品 shopping_cart 存放到文件 shopping_list.txt"""
    with open("shopping_list.txt",'a') as f:
        for k,v in shopping_cart:
            temp = k +'|'+ v
            f.write(temp)
            f.write('
')

def check_shopping_list():
    """查看文件 shopping_list.txt 中已购买的商品"""
    while True:
        with open("shopping_list.txt", 'r',encoding='utf-8') as f:
            for line in f:
                if line.strip():
                    print(line.strip())
            break

def check_or_buy():
    """查看文件shopping_list.txt中已购买的商品列表,还是购买商品"""
    while True:
        choice = input("1、查看购物车  2、购买商品
(q=quit)请输入: ")
        if choice.isdigit():
            choice = int(choice)
            if choice == 1:
                check_shopping_list()  # 调用购物车文件
                break
            elif choice == 2:
                break   # 结束本次循环,进入下一循环
            else:
                print("Incorrect input!")
        elif choice == "q":
            sys.exit("欢迎下次光临,请慢走!")
        else:
            print("33[31;1mIncorrect input!33[0m
")

def buy():
    while True:
        global salary # 在salary_isdigit()这个函数里面定义了salary,所以需要用global来引用它
        print("product list".center(30, '-'))
        show_product_list()  # 调用函数,展示商品列表
        choice = input("[c=check,q=quick]Do you want to buy? ")
        if choice.isdigit():
            choice = int(choice)
            if choice >= 0 and choice < len(product_list):
                p_item = product_list[choice]  # 选择的商品
                if int(p_item[1]) <= salary:  # 当价格小于salary就加入购物车
                    shopping_cart.append(p_item)
                    salary -= int(p_item[1])  # 扣钱
                    print("Add 33[31;1m%s33[0m to shopping cart,and your balance is 33[31;1m%s33[0m
" % (p_item, salary))
                else:
                    print("Your balance is 33[31;1m%s33[0m, not enough!
" % salary)
            else:
                print("33[31;1mProduct is not exist!33[0m
")
        elif choice == 'c':
            show_purchased()  # 调用函数
        elif choice == 'q':
            show_purchased()  # 调用函数
            shopping_list()   # 保存商品到文件中
            exit()
        else:
            print("33[31;1mIncorrect input, please try again!33[0m
")


shopping_cart = []

def main():
    while True:
        username = input("请输入用户名:")
        password = input("请输入密码:")
        f = login(username,password)
        if f:
            print("登录成功
")
            break
        else:
            print("登录失败,请重新登录
")
    check_or_buy()  # 调用函数,查看购物车还是购买商品
    salary_isdigit()   # 调用函数,判断salary是否数字,如果是则进行下一步
    buy()  # 调用函数,购买商品



if __name__ == '__main__':
    main()
原文地址:https://www.cnblogs.com/relax1949/p/7527329.html