python 练习之购物车

购物车程序
需求:用户输入工资,然后展示商品列表,用户输入需要购买的商品ID将商品添加到购物车,如果用的工资大于商品价格则加入购物车,如果小于那么将放弃该商品,用户退出时打印购买的商品和总价以及剩余的钱数。

#!/usr/bin/env python3

# -*- coding: utf-8 -*-

product_list = [
    ['Iphone7', 6500],
    ['MackBook', 12000],
    ['Python Book', 60],
    ['Coffee', 31],
    ['Bike', 999],
]


shopping_cart = []

salary = int(input("input your salary:"))

while True:
    for index, i in enumerate(product_list):
        print("%s.\t%s\t%s" % (index, i[0], i[1]))

    choice = input(">>:").strip()
    if len(choice) == 0:
        print("Not going back")
        continue

    if choice.isdigit():
        choice = int(choice)
        print(choice, len(product_list))
        if choice < len(product_list) and choice >= 0:
            product_item = product_list[choice] #获取商品
            if salary >= product_item[1]: #买的起
                salary -= product_item[1] #扣钱
                shopping_cart.append(product_item)
                print("Add %s into  your shopping cart, your current balance is %s" % (product_item[0], salary))
            else:
                print("Sorry, Cannot afford this product, still need", product_item[1]-salary)
        else:
            print("Cannot find this product")

    elif choice == "exit":
        total_cost = 0
        print("you have bought below products:")
        for i in shopping_cart:
            print(i)
            total_cost += i[1]

        print("Total cost:", total_cost)
        print("your current balance is", salary)
        break

 

 

2.带身份认证的购物车程序

#!/usr/bin/env python3

# -*- coding: utf-8 -*-

import time, os
shop_car2 = []
user_list = []
count = 0
user = "jiafei"
passwd = "123456"
input_user = input("Please input your username:").strip()
f = open("user.txt", 'a+')
lines = []
###将光标调整到0,否则读取不出来
f.seek(0)
for line in f.readlines():
    lines = line.replace("\n", "").split(",")
f.close()
for user in lines:
    if user == input_user:
        print("This user is locked, Please request to root!!!")
        exit()
    else:
        pass

while count < 3:
    if input_user == user:
        input_passwd = input("Please input password:")
        count += 1
        if count == 3:
            user_list.append(input_user)
            user = open("user.txt", "a")
            for input_user in user_list:
                user.write(input_user + ",")
            user.close()
        else:
            pass

        if input_passwd == passwd:
            print("login success!!!")
            #now_time = time.time()
            now_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
            title = "Welcome to shopping"
            print(now_time.center(40, "*"))
            print(title.center(40,"*"))
            shop_car = []
            product_list = [
                ["iphone 7", 5888],
                ["coffe", 30],
                ["computer", 3999],
                ["mac pro", 12000],
                ["bike", 300],
            ]

            filename = r"salary.txt"
            if os.path.exists(filename):
                temp = open("salary.txt", "r")
                for money in temp.readlines():
                    salary = money
                    print("您卡上月为:", salary)
            else:
                salary = input("请输入充值金额:")
            if salary.isdigit():
                salary = int(salary)

            while True:
                print("-----------product list----------")
                for i in enumerate(product_list):
                    print(i[0], i[1][0], i[1][1])
                choice = input("choice product_  quit to exit:")

                if choice.isdigit():
                    choice = int(choice)
                else:
                    continue
                if choice < len(product_list) and choice >= 0:
                    if salary >= product_list[choice][1]:
                        salary -= product_list[choice][1]
                        price = product_list[choice][1]
                        item = product_list[choice][0]
                        print("你购买了%s, 花费了%s, 余额为%s" % (item, price, salary))
                        shop_car.append(item)
                        shop_car2.append(price)
                    else:
                        print("你的余额不足,请选择其他商品,谢谢")
                        continue
                elif choice == "quit" or choice == "q":
                    print("您购买的商品如下:")
                    for product in shop_car:
                        print(product, shop_car.count(product))

                    total_price = sum(shop_car2)

                    print("总共消费了 %s" % total_price)
                    print("您的余额为%s" % salary)
                    print("欢迎下次再来,再见!!!")

                    salary_file = open("salary.txt", "w")
                    salary_file.write("%s" % salary)
                    salary_file.close()
                    exit()
                else:
                    print("没有该商品,请重新输入,谢谢")
                    continue
        else:
            print("This password is Error:")
    else:
        print("Can not this user")
        exit()

 

3.带有充值功能的购物车

#!/usr/bin/env python3

# -*- coding: utf-8 -*-


import time, os

shop_car2 = []
user_list = []
month = []
count = 0

user = "jiafei"
passwd = "123456"
message = "欢迎光临好邻居超市, 请登录"
print(message.center(50, "-"))
input_user = input("Please input your username:")
f = open("user.txt", 'a+')
lines = []
###将光标调整到0,否则读取不出来
f.seek(0)
for line in f.readlines():
    lines = line.replace("\n", "").split(",")
f.close()
for i in lines:
    if i == input_user:
        print("This user is locked, Please request to root!!!")
        exit()
    else:
        pass

while count < 3:
    if input_user == user:
        input_passwd = input("Please input your password:")
        count = count + 1

        if count == 3:
            user_list.append(input_user)
            user_file = open("user.txt", 'a')
            for i in user_list:
                user_file.write(i + ',')
                user_file.close()
        else:
            pass

        if input_passwd == passwd:
            print("login success!!!")
            now_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
            title = "Welcome to shopping"
            print(now_time.center(40, "*"))
            print(title.center(40, "*"))
            shop_car = []
            product_list = [
                ["iphone 7", 5888],
                ["coffe", 30],
                ["computer", 3999],
                ["mac pro", 12000],
                ["bike", 300],
            ]

            filename = r"salary.txt"
            if os.path.exists(filename):
                temp = open("salary.txt", "r")
                for money in temp:
                    salary = int(money)
                    print("您的卡上余额为%s" % salary)

                    chongzhi = input("按a充值,按b进入商城")
                    if chongzhi == "b":
                        pass
                    elif chongzhi == "a":
                        some_money = input("请输入充值金额:")
                        salary = salary + int(some_money)
                        print("充值成功,最新余额为%s" % salary)
                    else:
                        print("不能识别您的输入,请确认后再次输入,谢谢!!!")
                        continue
            else:
                salary = input("请输入充值金额:")
                if salary.isdigit():
                    salary = int(salary)

            while True:
                print("-----------product list----------")
                for i in enumerate(product_list):
                    print(i[0], i[1][0], i[1][1])
                choice = input("choice product_  quit to exit:")

                if choice.isdigit():
                    choice = int(choice)
                elif choice == "quit" or choice == "q":
                    print("您购买的商品如下:")
                    for product in shop_car:
                        print(product, shop_car.count(product))

                    total_price = sum(shop_car2)

                    print("总共消费了 %s" % total_price)
                    print("您的余额为%s" % salary)
                    print("欢迎下次再来,再见!!!")

                    salary_file = open("salary.txt", "w")
                    salary_file.write("%s" % salary)
                    salary_file.close()
                    exit()

                    exit()
                else:
                    continue

                if choice < len(product_list) and choice >= 0:
                    if salary >= product_list[choice][1]:
                        salary -= product_list[choice][1]
                        price = product_list[choice][1]
                        item = product_list[choice][0]
                        print("你购买了%s, 花费了%s, 余额为%s" % (item, price, salary))
                        shop_car.append(item)
                        shop_car2.append(price)
                    else:
                        money_deficiency = input("你的余额不足,请按“y”进行充值,按“q”返回商品列表,谢谢")
                        if money_deficiency == "y":
                            chongzhi_money = int(input("请输入充值金额:"))
                            salary = int(salary) + chongzhi_money

                            print("充值成功,最新余额为%s" % salary)
                            o = open("salary.txt", 'w')
                            o.write(str(salary))
                            o.close()
                            continue
                        elif money_deficiency == "q":
                            continue
                        else:
                            print("输入不合理,请重新输入,谢谢")
                            continue

                elif choice == "quit" or choice == "q":
                    print("您购买的商品如下:")
                    for product in shop_car:
                        print(product, shop_car.count(product))

                    total_price = sum(shop_car2)

                    print("总共消费了 %s" % total_price)
                    print("您的余额为%s" % salary)
                    print("欢迎下次再来,再见!!!")

                    salary_file = open("salary.txt", "w")
                    salary_file.write("%s" % salary)
                    salary_file.close()
                    exit()
                else:
                    print("没有该商品,请输入,谢谢")
                    continue
        else:
            print("This password is Error")
            continue
    else:
        print("can not this user")
        exit()

 

posted on 2018-03-06 08:55  李永山  阅读(180)  评论(0编辑  收藏  举报

导航