# -*- coding:utf-8 -*-
def regiter():
while True:
username = input("请输入您的账号:").strip()
password = input("请输入您的密码:").strip()#去除空格及换号符
with open('register',encoding='UTF-8')as f1:
for line in f1:#循环读取注册文件中的内容
line_list=line.strip().replace(',',',').split(',')#去除空格及换号符以及把中文逗号换成英文逗号
#print(type(line_list))
if username==line_list[0]:
print("用户名已经存在,请重新输入")
break
else:
with open('register', encoding='UTF-8',mode='a')as f2:
f2.write('\n{},{}'.format(username,password))
print("恭喜你注册成功%s"%username)
return True #结束函数
def login():
i=0#计数器
while i<3:#超过3次后,登陆失败
username = input("请输入您的账号:").strip()
password = input("请输入您的密码:").strip() # 去除空格及换号符
with open('register',encoding='UTF-8')as f1:
for line in f1:#循环读取注册文件中的内容
line_list=line.strip().replace(',',',').split(',')#去除空格及换号符以及把中文逗号换成英文逗号
#print(type(line_list))
if username==line_list[0]and password==line_list[1]:
print("*******登陆成功*******")
return True
else:
print("账户或密码输入错误")
i+=1
def shopping():
list_he=[]
offer=input("请输入您的储值卡金额:").strip()
if offer.isdigit():
offer=int(offer)
while True:
shipin2 = [['牛奶', 20], ['肉干', 30], ['大米', 15], ['面包', 15], ['啤酒', 3.5]]
for i, a in enumerate(shipin2, 1): # 循环打印商品列表
print("序号:%s" % i, "商品:%s" % a[0], "价格:%s元" % a[1])
huo_qu = input("请输入你要购买的商品,输入[0]退出").strip()
if huo_qu.isdigit():
huo_qu=int(huo_qu)
if huo_qu > 0 and huo_qu <= len(shipin2): # 验证输入是否正确
j = shipin2[huo_qu - 1] # 购买的商品和价格
if j[1] > offer: # 判断想要购买的商品价格是否超过了余额
print("您的余额不足,请及时充值")
else:
offer = offer - j[1] # 算出购买商品后的价格
print("您购买的商品为%s" % j[0], "剩余金额为%s" % offer) # 输出购买的商品
list_he.append(j[0]) # 把已购买商品添加至集合中
print("您已经购买了%s" % list_he) # 已购买商品集合
continue
elif huo_qu == 0:
print("退出程序,再见")
for m in list_he:
print("您购买了%s" % m)
break
else:
print("商城货物暂时短缺,请输入正确的商品序号")
else:
print("您输入的有非法字符,请重新输入")
choice_dict={
1:regiter,
2:login,
3:shopping
}
while True:
print('''-------欢迎光临购物商场-------
1:注册
2:登陆
3:购物
4:退出
''')
choice=input("请选择序号").strip()
if choice.isdigit():
choice=int(choice)
if choice>0 and choice<=len(choice_dict):
choice_dict[choice]()
else:
print("您输入的超出范围")
else:
print("您输入的有非法字符")
重构优化Python购物车
原文:http://blog.51cto.com/11258494/2120945