Python实现购物车程序
本文介绍了一个基于Python的购物车程序实现。程序支持用户输入工资、浏览商品列表、根据编号选购商品,并自动检测余额。若余额不足,用户可选择充值后继续购买。程序在退出时打印已购商品清单及剩余余额,适合Python初学者学习逻辑控制与数据处理。
本文分享一个Python购物车程序的实现案例,具体细节如下。
功能需求:
- 程序启动后,首先提示用户输入个人工资,随后展示商品列表。
- 支持用户通过输入商品编号来选购商品。
- 当用户选定商品后,系统会自动检查账户余额。如果余额充足,则直接扣除相应金额;如果余额不足,则提示用户。
- 用户可以在任意时刻选择退出程序,退出时系统将打印已购买的商品清单以及当前剩余余额。
- 如果余额不足,用户可以选择进行充值操作。
具体代码实现如下:
#coding=utf-8
#Version:python 3.6.0
#Tools:Pycharm 2017.3.2
_date_ = '2018/4/16/016 14:50'
_author_ = 'Hongyong'
salary = int(input("Please input your salary: "))
shoppingmart = []
items = (["1","Huawei","¥",2800],
["2","Earphone","¥",300],
["3","Book","¥",80])
msg_items = '''
----------items----------
1. Huawei ¥ 2800
2. Earphone ¥ 300
3. Book ¥ 80
-------------------------
'''
print(msg_items)
while True:
shopindex = int(input("Please choose goods: "))
if salary > items[shopindex-1][3]:
shoppingmart.append(items[shopindex-1])
salary -= int(items[shopindex-1][3])
print("You have bought {name} !".format(name = items[shopindex-1][1]))
print("Your balance is: ¥",salary)
decision = input("Do you want to quit now?")
print(msg_items)
else:
print("Your balance is not enough! Please try sth else.")
recharge_ans = input("Do you want to recharge?")
if recharge_ans == "y":
recharge = int(input("Please input money: "))
print("Please wait for a while...")
salary += recharge
print("You have recharged successfully!")
print("And the balance is: ",salary,"now!")
decision = input("Do you want to quit now?")
print(msg_items)
if decision == "q":
break
else:
continue
print("You have bought: ",shoppingmart)
print("Your balance is: ¥",salary)
print("Welcome your next coming!")
程序运行效果展示:
Please input your salary: 0 ----------items---------- 1. Huawei ¥ 2800 2. Earphone ¥ 300 3. Book ¥ 80 ------------------------- Please choose goods: 1 Your balance is not enough! Please try sth else. Do you want to recharge?y Please input money: 30000 Please wait for a while... You have recharged successfully! And the balance is: 30000 now! Do you want to quit now? ----------items---------- 1. Huawei ¥ 2800 2. Earphone ¥ 300 3. Book ¥ 80 ------------------------- Please choose goods: 1 You have bought Huawei ! Your balance is: ¥ 27200 Do you want to quit now? ----------items---------- 1. Huawei ¥ 2800 2. Earphone ¥ 300 3. Book ¥ 80 ------------------------- Please choose goods: 2 You have bought Earphone ! Your balance is: ¥ 26900 Do you want to quit now?q ----------items---------- 1. Huawei ¥ 2800 2. Earphone ¥ 300 3. Book ¥ 80 ------------------------- You have bought: [['1', 'Huawei', '¥', 2800], ['2', 'Earphone', '¥', 300]] Your balance is: ¥ 26900 Welcome your next coming!
以上就是本文的全部内容,希望对读者的学习有所帮助,也欢迎大家继续支持本站。
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









