第一个小程序:用户登录

看视频跟老师学Python,第一天的视频听的迷迷糊糊,最后老师的作业是自己写一个用户登录的小程序,在百般苦恼了好长时间以后还是反复看视频跟着老师做了出来。

一、作业及要求:

1、写一个用户登录的小程序;

2、要求已经存储用户名和密码的用户可以登录;

3、用户登录尝试次数为三次;

4、尝试超限后锁定该用户;

二、思路及知识点:

1、用户名和密码存储在account.txt文件里面;

2、锁定用户存储在lock.txt文件里面;

3、使用循环限制尝试次数;

4、使用if判断用户输入是否正确;

5、需要用到input(),Python2.x中是raw.input()

6、需要用到文件操作;

三、程序代码:

#!/usr/bin/env python
#    -.-    coding: utf-8    -.-

account_file = 'account.txt'
# 用户列表,包含用户名和密码
lock_file = 'lock.txt'
# 锁定用户列表
for i in range(3):
  username = input("username: ").strip()
  # .strip()去除用户输入中的空格
  password = input("password: ").strip()
  if len(username) !=0 and len(password) !=0:
    f = open(account_file)
    loginSuccess = False
    for line in f.readlines():
      line = line.split()
      if username  == line[0] and password == line[1]:
        # 用户输入的用户名和密码的判断
         print ("Welcon %s login my system" % username)
        loginSuccess = True
        break
    if loginSuccess is True:
        break
  else:
    continue
else:
  f = open(lock_file,'a')
  f.write('%s
' % username)
  f.close()
原文地址:https://www.cnblogs.com/sandler613/p/5295998.html