范例1:
# Version:python3.6.0
# Tools:Pycharm 2017.3.2
# author ="wlx"
__date__ = '2018/7/17 10:10'
goods = [
{"name": "电脑", "price": 1999},
{"name": "鼠标", "price": 10},
{"name": "游艇", "price": 20},
{"name": "美女", "price": 998},
]
user = {'alex':['123', -1, []]}
def display():
'''打印商品信息'''
print('========商品列表========')
for i in range(goods.__len__()):
print("{0}号商品:{1} 价格{2}".format(i, goods[i].get("name"), goods[i].get("price")))
print('========商品列表========')
def login(username, pwd):
# 判断用户名密码是否正确
if username in user:
if pwd == user.get(username)[0]:
return True
else:
print("\033[1;31;m密码输入错误,请重新输入\033[m")
return False
else:
print("\033[1;31;m无该用户,请重新输入\033[m")
return False
def buy_goods(username):
print("您的\033[1;31;m余额为{0}\033[m".format(user.get(username)[1]))
display()
no = int(input("请选择要购买的商品,输入对应的数字编号:"))
if user.get(username)[1] >= goods[no].get('price'): # 如果余额够买
user.get(username)[2].append(goods[no].get('name')) # 把买过的商品添加到已购买列表里
user.get(username)[1] = user.get(username)[1] - goods[no].get('price') # 更新余额
print('\033[1;31;m购买成功\033[m')
else: # 如果余额不够买
print("\033[1;31;m您的余额已不足,请选择其他商品购买:\033[m")
def query(username):
print("============已购买商品==========")
for item in user.get(username)[2]:
print(item)
print("============以上是已购买商品==========")
def delect():
while True:
print("=======选择你要进行的操作========")
d = input("输入1购买商品\n输入2查询已购买商品\n输入3退出:")
if d == '1':
buy_goods(username)
elif d == '2':
query(username)
elif d == '3':
query(username)
break
else:
print("\033[1;31;m输入错误请重输\033[m")
def buy(charge):
while charge:
if user.get(username)[1] == -1: # 余额为-1说明该用户没有登录过
salary = input("欢迎\033[1;31;m{0}\033[m,请输入您的工资:".format(username))
if salary.isdigit():
user.get(username)[1] = int(salary)+1+user.get(username)[1] # 更新余额
delect()
break
else: # 如果工资输入的不是纯数字
print("\033[1;31;m您输入的不是纯数字,请重新输入\033[m")
else: # 用户登录过
delect()
break
while True:
username = input("请输入用户名:")
pwd = input('请输入密码:')
charge = login(username,pwd) # 判断用户名密码是否正确
buy(charge) # 若用户名密码正确进入购买系统
范例2:
#! -*- coding: utf-8 -*-
# __author__: NeoWong
# __date__: 2018/3/28
goods = [
{"name": "电脑", "price": 1999},
{"name": "鼠标", "price": 10},
{"name": "游艇", "price": 20},
{"name": "美女", "price": 998},
]
with open('u_info', 'r', encoding='utf-8') as f: # 读取文件当中的用户信息
u_info = eval(f.read())
count = 3 # 设定尝试登陆的次数
while count: # 当可尝试的次数不为0
username = input('请输入您的用户名:\n').strip() # 读取用户输入的用户名
password = input('请输入您的密码:\n').strip() # 读取用户输入的密码
u_id = 0 # 定义用户列表的里面相应用户的索引变量
for user in u_info: # 匹配用户密码是否正确
if username == user['name'] and password == user['pwd']:
break
u_id += 1
else: # 若用户或密码不正确
count -= 1
print('用户名或密码错误!还可以尝试%s次!' % count) # 提示还可以尝试登陆的次数
continue
count = 0 # 退出程序的标准
money = u_info[u_id]['money'] # 将用户列表里面相应用户的工资提取出来放到变量中
print('您现在的工资有:\033[31;1m%s\033[0m' % money)
choice = input('您想要调整您的工资吗?(y/n):\n') # 询问用户是否要更改工资
if choice == 'y': # 若要更改工资
money = input('请输入您可用的工资:') # 输入工资
while not money.isdigit(): # 判断是否是数字
print('输入的工资必须是数字!')
money = input('请输入您可用的工资:')
money = int(money)
while True: # 循环显示可选的商品
print('您的工资有\033[31;1m%s\033[0m' % money)
print('商品:')
for i, j in enumerate(goods, 1):
print(i, j['name'], j['price'])
item_no = input('请输入您想购买的商品(按[check]查看购买记录,按[exit]退出购买):\n')
if item_no.isdigit(): # 若输入的字符为数字
item_no = int(item_no)
if (item_no >= 1) and (item_no <= len(goods)): # 若所输入的数字在合法范围内
item_no = item_no - 1
if money - goods[item_no]['price'] >= 0: # 若工资足以抵扣商品的价格
u_info[u_id]['shopping_cart'].append(goods[item_no]) # 加入购物车
money = money - goods[item_no]['price']
print('成功加入购物车')
else: # 若工资不足以抵扣
print('您的余额不足!')
else: # 若数字超出合法范围
print('该商品序号不存在,请输入正确的商品序号!')
elif item_no == 'check':
print('-----您已购买的商品-----')
print()
total = 0
for i, p_item in enumerate(u_info[u_id]['shopping_cart'], 1):
print(i, p_item['name'], p_item['price'])
total += int(p_item['price'])
print('总共消费:\033[31;1m%s\033[0m' % total)
print()
print('您当前的余额为:\033[31;1m%s\033[0m' % money)
while True:
q_key = input('按\033[31;1mq\033[0m回到购买页面!\n')
if q_key == 'q':
break
elif item_no == 'exit': # 若选择退出打印已购的商品以及总消费
print('-----您已购买的商品-----')
print()
total = 0
for i, p_item in enumerate(u_info[u_id]['shopping_cart'], 1):
print(i, p_item['name'], p_item['price'])
total += int(p_item['price'])
print('总共消费:\033[31;1m%s\033[0m' % total)
print()
print('您当前的余额为:\033[31;1m%s\033[0m' % money)
u_info[u_id]['money'] = money
break
else: # 若输入字符不合法
print('该商品序号不存在,请输入正确的商品序号!')
else:
print('-----欢迎下次光临!-----')
with open('u_info', 'w', encoding='utf-8') as f: # 将更新后的用户信息写入文件
f.write(str(u_info))