【Python 学习_第1周_程序代码】金角大王培训第一周作业_输入用户名和密码,根据输入内容进行结果判定(包含excel表格读写操作)

需求描述:

  • 输入用户名密码
  • 认证成功后显示欢迎信息
  • 输错三次后锁定

程序编写

    采用 excel 文件记录程序需求信息,文件包含2个sheet, 第1个 sheet 用于存储 用户名和密码,sheet名称 为user_info;第二个 sheeet 用于记录存储 锁定账户,名称为use_locked

程序流程图

输出代码:


#导入读取excel表格模块
import xlrd
#导入写入excel表格模块
import xlwt
from xlutils.copy import copy

style = xlwt.easyxf('font:height 240, color-index red, bold on;align: wrap on, vert centre, horiz center')

#读入excel文件地址
address_of_excel_file = r"F:Python_trainingday1user_name.xls"

#读取表格
read_of_excel_file = xlrd.open_workbook(address_of_excel_file,formatting_info=True)
#print("表格中表单名称: ",read_of_excel_file.sheet_names())

#读取用户信息表单及表单行数
sheet_of_user_info = read_of_excel_file.sheet_by_name(read_of_excel_file.sheet_names()[0])
rows_of_sheet_of_user_info = sheet_of_user_info.nrows
clos_of_sheet_of_user_info = sheet_of_user_info.ncols
#print("用户名密码表单行数: ",rows_of_sheet_of_user_info)


#print('锁定用户行数',rows_of_user_lock)
flag_for_user_lock = 0
flag_for_user_log_success = 0
flag_for_user_log_failure = 0
count_of_wrong_input = 0
# user_info = sheet_of_user_info.cell_value(1,1)
# print(user_info)
# print(type(user_info))

while count_of_wrong_input<3:

# 读取锁定用户信息及表单行数
sheet_of_user_lock = read_of_excel_file.sheet_by_name(read_of_excel_file.sheet_names()[1])
rows_of_user_lock = sheet_of_user_lock.nrows
user_name = input("请输入用户名:")
password = input("请输入密码:")

#判定用户名是否已经锁定
for i in range((rows_of_user_lock)):
user_locked = sheet_of_user_lock.cell_value(i,0)
#print(user_locked)
if user_locked == user_name:
flag_for_user_lock = 1
break

if flag_for_user_lock == 1:
print("提示用户名已经被锁定 ,请拨打电话10096解除锁定")
break
else:
for i in range((rows_of_sheet_of_user_info)):
user_info = sheet_of_user_info.cell_value(i,0)
#print("存储的用户名:",user_info)
if user_info == user_name:
if password == sheet_of_user_info.cell_value(i,1):
flag_for_user_log_success = 1
else:
count_of_wrong_input = count_of_wrong_input + 1
flag_for_user_log_failure = 1
if flag_for_user_log_success == 1 or flag_for_user_log_failure == 1:
break
else:
print("您输入的用户名错误,请重新输入")



#用户名、密码验证通过,提醒欢迎归来
if flag_for_user_log_success == 1:
flag_for_user_log_success = 0
print("欢迎%s主人归来"%user_name)
break

#用户名、密码输入错误,提醒再次输入
if flag_for_user_log_failure == 1:
flag_for_user_log_failure = 0
if count_of_wrong_input<3:
print("这是您第%d次用户名密码输入错误,输入错误三次后系统将锁定账户,您是否重试? "%count_of_wrong_input)
decision_of_input = input("再次输入请输入y,不输入请输入其他任意键")
if decision_of_input == 'y':
continue
else:
break
else:
#写入文件
#read_of_excel_file.sheet_by_name(read_of_excel_file.sheet_names()[1])
wb = copy(read_of_excel_file)
ws = wb.get_sheet(1)
#ws.write(rows_of_user_lock, 0, user_name, style)
ws.write(rows_of_user_lock, 0, user_name, style)
wb.save(address_of_excel_file)
else:
count_of_wrong_input = 0
print("提示由于用户名密码输入三次错误,用户名已经被锁定 ,请拨打电话10096解除锁定")

备注:代码标红部分表示 文件扩展名需为.xls ,若为 xlsx则 会报错
此程序默认用户每次输入相同用户名,属于程序bug

原文地址:https://www.cnblogs.com/Finding-bugs/p/9092181.html