首页 技术 正文
技术 2022年11月9日
0 收藏 577 点赞 3,526 浏览 4171 个字

购物车程序

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/3/6 21:01
# @Author : hyang
# @Site :
# @File : shop_cart.py
# @Software: PyCharm"""
购物车程序
数据结构:
goods = [
{"name": "电脑", "price": 1999},
{"name": "鼠标", "price": 10},
{"name": "游艇", "price": 20},
{"name": "美女", "price": 998},
......
]功能要求:
基础要求:1、启动程序后,输入用户名密码后,让用户输入工资,然后打印商品列表2、允许用户根据商品编号购买商品3、用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒4、可随时退出,退出时,打印已购买商品和余额5、在用户使用过程中, 关键输出,如余额,商品已加入购物车等消息,需高亮显示扩展需求:1、用户下一次登录后,输入用户名密码,直接回到上次的状态,即上次消费的余额什么的还是那些,再次登录可继续购买2、允许查询之前的消费记录
"""
import os# 商品列表
goods = [
{"name": "电脑", "price": 1999},
{"name": "鼠标", "price": 10},
{"name": "游艇", "price": 20},
{"name": "IPAD", "price": 1998},
{"name": "手机", "price": 998},
{"name": "玩具", "price": 50},
{"name": "教科书", "price": 100}
]last_shop = [] # 上次购买数据
last_bal = [] # 得到每次购买余额def is_shop(user):
"""
判断该用户是否已消费数据
:param user:
:return:
"""
flg = False
if os.path.exists(r"user_shop.txt"):
# 查询用户有购买记录
with open(r"user_shop.txt", "r", encoding='utf-8') as f:
for line in f:
if line.find(user) != -1:
flg = True
break
else: # 创建空文件
with open(r"user_shop.txt", "w", encoding='utf-8') as f:
f.write("")
return flgdef login():
"""
用户登录
:return:
"""
err_cnt = 0
suc_user = '' # 返回成功登录用户
# 判断锁标志
while err_cnt < 3:
user = input('输入用户名: ')
pwd = input('输入密码: ')
if user == 'alex' and pwd == '':
print('登录成功')
suc_user = user
break
else:
print('登录失败')
err_cnt += 1
else:
print('您登录失败已超过3次')
return suc_userdef check_salary():
"""
检查收入
:return:
"""
while True:
salary = input('输入工资: ')
if salary.isdigit():
break
else:
print('工资输入错误,请重新输入!')
return int(salary)def shop(user, salary):
"""
用户购物
"""
shop_cart = [] # 购物车
while True:
print('-------商品列表--------')
for index, value in enumerate(goods):
print('商品编号:%s 商品名称:%s 商品价格:%s' % (index, value['name'], value['price'])) choice = input('输入商品编号:---输入q退出购买 ')
if choice.isdigit():
choice = int(choice)
if 0 <= choice < len(goods):
price = goods[choice]['price']
if (salary - price) > 0:
salary = salary - price
shop_cart.append(goods[choice])
print('\033[1;32;40m购买商品编号:%s 购买商品名称:%s 购买商品价格:%s\033[0m'
% (choice, goods[choice]['name'], goods[choice]['price']))
print('\033[1;32;40m工资余额=%s\033[0m' % salary)
else:
print('余额不足')
continue
else:
print('商品编号不存在!') elif choice == 'q':
print('\033[1;31;40m-------本次购物退出--------\033[0m')
if len(shop_cart) > 0:
print('-------本次购买商品列表--------')
with open(r"user_shop.txt", "a+", encoding='utf-8') as f:
f.write("user:%s\n" % user)
for value in shop_cart:
shop_info = '购买商品名称:%s|购买商品价格:%s' % (value['name'], value['price'])
print('\033[1;32;40m%s\033[0m' % shop_info)
f.write(shop_info + "\n")
bal_info = '工资余额:%s' % salary
print('\033[1;32;40m%s\033[0m'% bal_info)
f.write(bal_info + "\n")
breakdef get_shop(user):
"""
读取文件得到用户已消费数据
:param user:
:return:
"""
flg = False
resume_goods = [] # 消费商品
with open(r"user_shop.txt", "r", encoding='utf-8') as f:
for line in f:
if line.find("购买") != -1:
shop_li = line.split("|")
resume_goods.append([shop_li[0].split(":")[1].strip(), shop_li[1].split(":")[1].strip()])
elif line.find("余额") != -1:
last_bal.append(line.split(":")[1].strip())
print("\033[1;32;40m历史购物:%s\033[0m" % resume_goods) # 带绿色输出
print('\033[1;32;40m还剩下余额:%s\033[0m' % last_bal[-1]) # 带绿色输出if __name__ == '__main__':
user = login()
if user != '':
print('{}登录成功'.format(user))
while True:
action = input('输入c查询消费记录,输入b购买商品,输入q退出:')
if action == 'q':
print('\033[1;31;40m---退出程序------\033[0m') # 带红色输出
get_shop(user)
break
elif action == 'c':
if is_shop(user):
print("---查询之前的消费记录---")
get_shop(user)
else:
print("---查询之前无消费记录---")
elif action == 'b':
if not is_shop(user):
salary = check_salary()
else:
salary = int(last_bal[-1])
print('您工资现有:', salary)
shop(user, salary)

输出结果

python基础练习题

python基础练习题

三级菜单程序

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time : 2018/3/1 9:38
# @Author : hyang
# @File : three_menu.py
# @Software: PyCharm
"""
可依次选择进入各子菜单
可从任意一层往回退到上一层
可从任意一层退出程序
"""
menu = {
'北京':{
'海淀':{
'五道口':{
'soho':{},
'网易':{},
'google':{}
},
'中关村':{
'爱奇艺':{},
'汽车之家':{},
'youku':{},
},
'上地':{
'百度':{},
},
},
'昌平':{
'沙河':{
'老男孩':{},
'北航':{},
},
'天通苑':{},
'回龙观':{},
},
'朝阳':{},
'东城':{},
},
'上海':{
'闵行':{
"人民广场":{
'炸鸡店':{}
}
},
'闸北':{
'火车站':{
'携程':{}
}
},
'浦东':{},
},
'山东':{},
}current_menu = menu # 当前菜单
last_menu = [] # 上层菜单
prompt = "输入菜单名,进入子菜单\n 输入'b',返回上层菜单\n 输入'q',退出程序\n"
while True:
if len(current_menu) == 0:
print('已经到最底层,该菜单下无节点')
else:
for k in current_menu:
print('菜单->', k)
input_str = input(prompt).strip()
if input_str == 'q':
print('退出程序')
break
elif input_str in current_menu:
last_menu.append(current_menu) # 保存上一层菜单
current_menu = current_menu[input_str] # 保存当前层
elif input_str == 'b':
if len(last_menu) != 0:
current_menu = last_menu.pop() # 弹出上一层菜单
else:
print('已经是顶层菜单')
else:
print('该节点菜单不存在')
continue
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,492
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,907
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,740
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,495
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,133
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,297