用户登录——三次锁定
dic = {
'egon1': {'password': '123', 'count': 0},
'egon2': {'password': '123', 'count': 0},
'egon3': {'password': '123', 'count': 0},
}
while True:
name = input('请输入用户姓名:')
if not name in dic:
print('用户姓名不存在')
continue
elif dic[name]['count'] > 2:
print('用户已被锁定')
continue
password = input('请输入密码:')
if password == dic[name]['password']:
print('登录成功')
break
else:
print('用户名错误')
dic[name]['count'] += 1
存取款——基本功能
def withdraw():
print('取款')
def trnfer():
print('转账')
def check_balance():
print('查询余额')
func_dic = {
'1': ['取款', withdraw],
'2': ['转账', trnfer],
'3': ['查询余额', check_balance]
}
while True:
print('0 退出')
for k, v in func_dic.items():
print(k, v[0])
choice = input('请输入业务').strip()
if choice == '0': # 要加引号,input的是字符串
break
if choice in func_dic:
func_dic[choice][1]()
else:
print('输入错误!')
购物车——基本功能
menu = {}
dic = {
'apple': 10,
'tesla': 100000,
'mac': 3000,
'lenovo': 30000,
'cehkin': 10
}
while True:
for name, price in dic.items():
print(name, price)
goods_name = input('请输入商品:').strip()
if not goods_name in dic:
print('商品不存在')
goods_count = input('请输入购买数量:').strip()
if not goods_count.isdigit():
print('请输入整数')
continue
goods_count = int(goods_count)
price = dic[goods_name]
if not goods_name in menu:
menu[goods_name] = [price, goods_count]
else:
menu[goods_name][1] += goods_count
print(menu)
装饰器——模板
def outter(func):
def wrapper(*args,**kwargs):
pass
res=func(*args,**kwargs)
return res
return wrapper
装饰器——时间模块
import time
def index(): # index=被装饰对象index函数的内存地址
time.sleep(1)
print('测试成功')
def timer(func): # func=被装饰对象index函数的内存地址
def wrapper(*args, **kwargs):
start = time.time()
res = func(*args, **kwargs) # 被装饰对象index函数的内存地址(x,y,z)
stop = time.time()
print('测试用时为%s' % (stop - start))
return res # 千万不能有括号
return wrapper#当初是全局的,所以要retrun
index = timer(index) # timer(被装饰对象index函数的内存地址)->返回wrapper函数
res = index() # wrapper()
综合——装饰器+字典,存取款基本功能
func_dic = {}
# 往空字典里传值
def outter(n, msg):
def inner(func):
# 添加记录
func_dic[str(n)] = [msg, func]
return inner
# func_dic = {
# '1': ['提现', withdraw],
# '2': ['转账', transfer],
# '3': ['查询余额', check_balance]
# }
@outter('1', '提现') # @inner->inner(withdraw)
def withdraw():
print('提现功能')
@outter('2', '转账')
def transfer():
print('转账功能')
@outter('3', '查询余额')
def check_balance():
print('查询余额')
def run():
while True:
for k, v in func_dic.items():
print(k, v[0])
choice = input('请输入命令编号,输入q退出').strip()
if choice == 'q':
print('退出')
break
if choice in func_dic:
func_dic[choice][1]()
else:
print('输入错误!请重新输入')
run()