小程序5:注册和登录

注册代码:

# -*- coding: utf-8 -*-
# !/user/bin/env python
file = open(r'C:UserszxqDesktopuserinfo.txt','a')  #在‘a’是写的方式打开,不可读
while True:
account = raw_input('请输入你要注册的账号:')
if account == ' ':
print('你再输入一遍账号:')
continue
passwd = raw_input('请输入你要输入的密码:')
if passwd == ' ':
print('你再输入一遍密码:')
continue
str = '%s:%s ' % (account,passwd)  
#字符串格式化,注意字符串后加 ;登录取密码时,应截取掉
file.write(str)
file.flush()  
#把缓冲区的数据刷新到磁盘上
print('恭喜您注册成功。')
break
file.close()

 运行时:输入的注册账号和密码都会以%s:%s 的格式保存在userinfo.txt文件中

登录代码:

# !/user/bin/env python
# -*- coding: utf-8 -*-
file = open(r'C:UserszxqDesktopuserinfo.txt','r')  #以只读方式打开userinfo.txt
num = 0
while True:
if num == 0:
account = raw_input('登录账号:')
if account == '':
print('请再输入一遍账号')
continue
passwd = raw_input('登录密码:')
if passwd == '':
print('请再输入一遍密码')
continue

for str in file:
file_account = str.split(':')[0]  
#把每次循环的str进行切片,以 : 为切片标准;根据索引取出账号
file_passwd = str.split(':')[1]  
#根据索引取出密码
file_passwd = file_passwd[:-1] 
 #对上一个file_passwd变量进行切片;切掉密码最后一个字符,即

if file_account == account and file_passwd == passwd: 
 #当输入的accounts、passwd和文件userinfo.txt中的file_account、file_passwd一致时,即登录成功,break退出for循环
print('登录成功')
num = 1
break
if num == 1: 
 #如果num=1退出while循环
break

  加num参数是为了退出while循环

  运行时:输入的账号和密码不在文件userinfo.txt文件中时,就一直循环让登录账号,知道输入正确提示登录成功,退出while循环

原文地址:https://www.cnblogs.com/zzfighting/p/5715926.html