Python 基础

作业要求:

1. 用户输入帐号密码进行登陆

2. 用户信息保存在文件内

3. 用户密码输入错误三次后锁定用户

知识点总结:

1. file的操作: with open 

2. 读取file信息, 从string 转为 list  

3. 读取file信息, 从string 转为list, 专为字典 (此处注意,是一一添加的)

4. 字符串格式化输出 (%) : % user_name, psw               注意没有parenthese

5. 最后须仔细测试,同时调整代码逻辑及格式。 

MY WORK

#!usr/bin/env python
# -*- coding:utf-8 -*-
# Author: Jane Yue

import sys


locked_list
= [] # 题点:将file信息 读到 List里 with open('locked_file', 'r+') as f: for line in f.readlines(): locked_list.append(line.strip()) # print返回值:['BigHead'] user_info = {} with open('user_info', 'r+') as f: for line in f.readlines(): user_list = line.strip().split() # 题点:将string变3个list user_info[user_list[0]] = user_list[1] # 题点:将 list加到 dictionary def login(): # 定义 login 函数 count = 3 while count >= 0: psw = input('Password: ') # 输入password if psw == user_info.get(user_name): print('Welcome to login, %s' % user_name) sys.exit() else: count -= 1 if count > 0: print("Login incorrect. You can try another %d times" % count) continue else: print('You account has been blocked. Please contact the administrator') with open('locked_file', 'a') as f1: f1.write(" %s" % user_name) sys.exit() while True: user_name = input('Username: ') # 主程序 if user_name in user_info.keys(): if user_name in locked_list: print('Your account has been blocked, please contact the administrator') else: login() else: print('Username does not exist') continue

SAMPLE 1: By 刘

步骤:

1. 字符串读取转成字典

user_info = 'Eric:123456#Catherine:098765'
user_list = user_info.split('#')
print(user_list)

user_dic ={}      # 创建空字典
for item in user_list:
    item_list = item.split(':')  # >>> ['eric','123456',''Catherine','098765']
    user_dic[item_list[0]] = item_list[-1]   #???
print(user_dic)

 {'Eric': '123456', 'Catherine': '098765'}

2. 从文件中读取字符串

f = open('user_info.txt','r')
user_info = f.read()
f.close()

user_list = user_info.split('#')
print(user_list)

user_dic ={}      # 创建空字典
for item in user_list:
    item_list = item.split(':')  # >>> ['eric','123456',''Catherine','098765']
    user_dic[item_list[0]] = item_list[-1]   #
print(user_dic)

3. 程序的主要部分

import sys

user_info = {'alex': "123",'wenwei': 'gdalex'}

count = 0
username = input('用户名 >>> : ')
if username in user_info:
    # lock_list = 读取锁定文件的信息
    lock_list = ['alex']
    if user_info in lock_list:
        print('被锁定')
        sys.exit()
    else:
        while count < 3:
            password = input('pwd >>>:')
            if password == user_info[username]:
                print('登陆成功,欢迎%s' % username)
                sys.exit()
            else:
                count += 1
                if count == 3:
                    print('被说点,请联系管理员')
                    sys.exit()
                else:
                    print('密码错误!请重新输入。还有%s次机会' % (3-count))
else:
    print('用户名不存在')

 MY WORK:

原文地址:https://www.cnblogs.com/lg100lg100/p/7123240.html