刚开始学习python,一边学,一边写下自己的收获,与同在路上的你分享!如有错误,请大牛批评指正。
题目:编写一个用户登录程序,根据用户名和密码登录,可登录三次,如果重复登录三次错误则将该用户锁定,重启程序再次以该用户的用户名和密码登录提示被锁定。
我自己的代码如下:
user = ['张三','李四','王五']
passw=[123,234,567]
choice=0
count=[0,0,0]
while choice<3:
name = input("请输入用户名:")
password = int(input("请输入密码:"))
if name in user:
index=int(user.index(name))
with open("limit.txt") as f:
read=f.read()
f.close()
if (len(read))==0:
authority = ['open','open','open']
else:
authority=read.split(',')
if authority[index]=='open':
if password == passw[index]:
print("登录成功")
break
else:
print("密码错误")
count[index] += 1
if count[index]==3:
authority[index]='lock'
write=','.join(authority)
print(write)
with open('limit.txt','w') as g:
g.write(write)
g.close()
else:
print("重新登录机会早已用完,账号被锁定")
else:
print("用户名不存在")
choice += 1
这里主要说一下,用户的状态被记录在authority这个list中,首先,当写入的时候,如果直接write入文件是会提示类型应该为str,可是强制转换成str依然会报异常,那么你这时候就有点慌了,不要急,试试.jion() 方法吧,在使用完以后如果尝试输出一下write变量的类型,你会发现类型也变成了str,是不是很神奇
同理,读的时候试试.split() 吧!
好好领悟,谢谢阅读!