三级菜单

要求:

打印省、市、县三级菜单
可返回上一级
可随时退出程序

购物车程序

要求:

用户名和密码存放于文件中,格式为:egon|egon123
启动程序后,先登录,登录成功则让用户输入工资,然后打印商品列表,失败则重新登录,超过三次则退出程序
允许用户根据商品编号购买商品
用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒
可随时退出,退出时,打印已购买商品和余额

menu = {
'北京':{
'海淀':{
'五道口':{
'soho':{},
'网易':{},
'google':{}
},
'中关村':{
'爱奇艺':{},
'汽车之家':{},
'youku':{},
},
'上地':{
'百度':{},
},
},
'昌平':{
'沙河':{
'老男孩':{},
'北航':{},
},
'天通苑':{},
'回龙观':{},
},
'朝阳':{},
'东城':{},
},
'上海':{
'闵行':{
"人民广场":{
'炸鸡店':{}
}
},
'闸北':{
'火车战':{
'携程':{}
}
},
'浦东':{},
},
'山东':{},
} #part1(初步实现):能够一层一层进入
layers = [menu, ] while True:
current_layer = layers[-1]
for key in current_layer:
print(key) choice = input('>>: ').strip() if choice not in current_layer: continue layers.append(current_layer[choice]) #part2(改进):加上退出机制
layers=[menu,] while True:
if len(layers) == 0: break
current_layer=layers[-1]
for key in current_layer:
print(key) choice=input('>>: ').strip() if choice == 'b':
layers.pop(-1)
continue
if choice == 'q':break if choice not in current_layer:continue layers.append(current_layer[choice])

三级菜单

import os

product_list = [['Iphone7',5800],
['Coffee',30],
['疙瘩汤',10],
['Python Book',99],
['Bike',199],
['ViVo X9',2499], ] shopping_cart={}
current_userinfo=[] db_file=r'db.txt' while True:
print('''
登陆
注册
购物
''') choice=input('>>: ').strip() if choice == '':
#1、登陆
tag=True
count=0
while tag:
if count == 3:
print('\033[45m尝试次数过多,退出。。。\033[0m')
break
uname = input('用户名:').strip()
pwd = input('密码:').strip() with open(db_file,'r',encoding='utf-8') as f:
for line in f:
line=line.strip('\n')
user_info=line.split(',') uname_of_db=user_info[0]
pwd_of_db=user_info[1]
balance_of_db=int(user_info[2]) if uname == uname_of_db and pwd == pwd_of_db:
print('\033[48m登陆成功\033[0m') # 登陆成功则将用户名和余额添加到列表
current_userinfo=[uname_of_db,balance_of_db]
print('用户信息为:',current_userinfo)
tag=False
break
else:
print('\033[47m用户名或密码错误\033[0m')
count+=1 elif choice == '':
uname=input('请输入用户名:').strip()
while True:
pwd1=input('请输入密码:').strip()
pwd2=input('再次确认密码:').strip()
if pwd2 == pwd1:
break
else:
print('\033[39m两次输入密码不一致,请重新输入!!!\033[0m') balance=input('请输入充值金额:').strip() with open(db_file,'a',encoding='utf-8') as f:
f.write('%s,%s,%s\n' %(uname,pwd1,balance)) elif choice == '':
if len(current_userinfo) == 0:
print('\033[49m请先登陆...\033[0m')
else:
#登陆成功后,开始购物
uname_of_db=current_userinfo[0]
balance_of_db=current_userinfo[1] print('尊敬的用户[%s] 您的余额为[%s],祝您购物愉快' %(
uname_of_db,
balance_of_db
)) tag=True
while tag:
for index,product in enumerate(product_list):
print(index,product)
choice=input('输入商品编号购物,输入q退出>>: ').strip()
if choice.isdigit():
choice=int(choice)
if choice < 0 or choice >= len(product_list):continue pname=product_list[choice][0]
pprice=product_list[choice][1]
if balance_of_db > pprice:
if pname in shopping_cart: # 原来已经购买过
shopping_cart[pname]['count']+=1
else:
shopping_cart[pname]={'pprice':pprice,'count':1} balance_of_db-=pprice # 扣钱
current_userinfo[1]=balance_of_db # 更新用户余额
print("Added product " + pname + " into shopping cart,\033[42;1myour current\033[0m balance " + str(balance_of_db)) else:
print("买不起,穷逼! 产品价格是{price},你还差{lack_price}".format(
price=pprice,
lack_price=(pprice - balance_of_db)
))
print(shopping_cart)
elif choice == 'q':
print("""
---------------------------------已购买商品列表---------------------------------
id 商品 数量 单价 总价
""") total_cost=0
for i,key in enumerate(shopping_cart):
print('%22s%18s%18s%18s%18s' %(
i,
key,
shopping_cart[key]['count'],
shopping_cart[key]['pprice'],
shopping_cart[key]['pprice'] * shopping_cart[key]['count']
))
total_cost+=shopping_cart[key]['pprice'] * shopping_cart[key]['count'] print("""
您的总花费为: %s
您的余额为: %s
---------------------------------end---------------------------------
""" %(total_cost,balance_of_db)) while tag:
inp=input('确认购买(yes/no?)>>: ').strip()
if inp not in ['Y','N','y','n','yes','no']:continue
if inp in ['Y','y','yes']:
# 将余额写入文件 src_file=db_file
dst_file=r'%s.swap' %db_file
with open(src_file,'r',encoding='utf-8') as read_f,\
open(dst_file,'w',encoding='utf-8') as write_f:
for line in read_f:
if line.startswith(uname_of_db):
l=line.strip('\n').split(',')
l[-1]=str(balance_of_db)
line=','.join(l)+'\n' write_f.write(line)
os.remove(src_file)
os.rename(dst_file,src_file) print('购买成功,请耐心等待发货') shopping_cart={}
current_userinfo=[]
tag=False else:
print('输入非法') else:
print('\033[33m非法操作\033[0m')

购物车-面条版

python基础-小练习的更多相关文章

  1. python基础小知识,is和==的区别,编码和解码

    1.is和==的区别 1)id() 通过id()我们可以查看到一个变量表示的值在内存中的地址 >>> s1 = "Tanxu" >>> s2 = ...

  2. python基础--小数据池,代码块的最详细、深入剖析

    本文转至太白金星 一,id,is,== 在Python中,id是什么?id是内存地址,那就有人问了,什么是内存地址呢? 你只要创建一个数据(对象)那么都会在内存中开辟一个空间,将这个数据临时加在到内存 ...

  3. python基础小点

    变量的命名规则 由字母.下划线.数字组成,且不能以数字开头 不能用关键字作为变量名 最好不要与python内置的一些方法和类名冲突 变量名应尽量简短且具有意义,多个单词之间用下划线连接 注释 #  - ...

  4. Python基础-小程序练习(跳出多层循环,购物车,多级菜单,用户登录)

    一. 从第3层循环直接跳出所有循环 break_flag = False count = 0 while break_flag == False: print("-第一层") wh ...

  5. python基础小练习

    def main(): number = int(input("请输入学生的总人数:")) # 输入要录入的学生总数 count = number # 用一个变量来保存这个学生总数 ...

  6. python基础之 数据类型的补充,小数据类型

    1.id is详解 ID 在Python中,id是什么?id是内存地址,比如你利用id()内置函数去查询一个数据的内存地址: name = 'nba' print(id(name)) # 158583 ...

  7. Python基础知识(六)------小数据池,集合,深浅拷贝

    Python基础知识(六)------小数据池,集合,深浅拷贝 一丶小数据池 什么是小数据池: ​ 小数据池就是python中一种提高效率的方式,固定数据类型使用同一个内存地址 代码块 : ​ 一个文 ...

  8. python基础练习-猜年龄、编写登陆接口小程序

    python基础练习:   一.猜年龄 , 可以让用户最多猜三次! age=40 count = 1 while count <=3 : user_guess=int(input("i ...

  9. Python开发【第二篇】:Python基础知识

    Python基础知识 一.初识基本数据类型 类型: int(整型) 在32位机器上,整数的位数为32位,取值范围为-2**31-2**31-1,即-2147483648-2147483647 在64位 ...

随机推荐

  1. RestTemplate的逆袭之路,从发送请求到负载均衡

    上篇文章我们详细的介绍了RestTemplate发送请求的问题,熟悉Spring的小伙伴可能会发现:RestTemplate不就是Spring提供的一个发送请求的工具吗?它什么时候具有了实现客户端负载 ...

  2. SpringBoot入门教程(五)Java基于MySQL实现附近的人

    “附近的人”这个功能估计都不陌生,与之类似的功能最开始是在各大地图应用上接触过,比如搜附近的电影院,附近的超市等等.然而真正让附近的人火遍大江南北的应该是微信"附近的人"这个功能, ...

  3. SpringBoot技术栈搭建个人博客【项目准备】

    前言:很早之前就想要写一个自己的博客了,趁着现在学校安排的实习有很多的空档,决定把它给做出来,也顺便完成实习的任务(搞一个项目出来...) 需求分析 总体目标:设计一套自适应/简洁/美观/易于文章管理 ...

  4. Linux下 Vim(Vi)编辑器的使用

    vi编辑器 vi是UNIX和类UNIX环境下的可用于创建文件的屏幕编辑器.vi有两种工作模式:命令模式和文本输入模式.启动vi需要输入vi,按[Spacebar]键并输入文件名后回车. 切换模式键 v ...

  5. ASP.NET Core 2.1 : 十.升级现有Core2.0 项目到2.1

    .NET Core 2.1 终于发布了, 赶紧升级一下. 一. 安装SDK 首先现在并安装 SDK(64-bit) 安装完毕后如果新建项目可以看到已经有2.1的选项了 二. 更新现有2.0项目到2.1 ...

  6. JVM(五)垃圾回收器的前世今生

    全文共 2195 个字,读完大约需要 8 分钟. 如果垃圾回收的算法属于内存回收的方法论的话,那本文讨论的垃圾回收器就属于内存回收的具体实现. 因为不同的厂商(IBM.Oracle),实现的垃圾回收器 ...

  7. [Go] Go的WaitGroup计数信号量

    WaitGroup是一个计数信号量,可以用来记录并维护运行的goroutine,如果WaitGroup的值大于0,Wait方法就会阻塞 调用Done方法来减少WaitGroup的值,并最终释放main ...

  8. C#获得指定目录床架时间、更新时间和最后访问时间等信息的代码

    将做工程过程常用的内容片段备份一次,下面的内容内容是关于C#获得指定目录床架时间.更新时间和最后访问时间等信息的内容,希望能对小伙伴们也有用. using System;using System.IO ...

  9. 数据库H2学习

    本文转载自:https://www.cnblogs.com/xdp-gacl/p/4171024.html 一.H2数据库介绍 常用的开源数据库有:H2,Derby,HSQLDB,MySQL,Post ...

  10. SQL Server -- 回忆笔记(四):case函数,索引,子查询,分页查询,视图,存储过程

    SQL Server知识点回忆篇(四):case函数,索引,子查询,分页查询,视图,存储过程 1. CASE函数(相当于C#中的Switch) then '未成年人' else '成年人' end f ...