python - 登录认证系统
问题描述
我正在为我提议的一个学校项目制作一个 python 登录系统,我遇到了一个我找不到的逻辑错误。该程序应该允许三次登录尝试,并且在您登录时应该显示“正确”,但是程序运行并且当您输入正确的用户名和密码时,它会打印“您输入了错误的密码”并循环程序,然后当您输入任何值时,它会停止程序并且什么都不会显示。你能帮我找出逻辑错误吗?我很乐意解释任何功能的作用:)
def logging():
atmptcount = 0
usr = input('Please enter your username: ')
pas = input('Please enter your password: ')
while atmptcount != 3:
for line in login:
log = line.split(',')
if usr == log[0] and pas == log[1]:
print('correct')
elif usr != log[0] and pas != log[1]:
atmptcount = atmptcount + 1
print('Sorry you have entered your details incorrectly, please try again')
logging()
logging()
解决方案
这里的逻辑有点缺陷,我已经稍微纠正了——不过你的思路是对的!
首先,您要求用户在while
循环之外进行输入。这意味着每次循环返回时,用户都没有机会输入新的详细信息。
其次,根据您的elif
声明,每次用户/通行证与login
列表中的行不匹配时都会运行。我们通过仅在浏览整个文件但未找到匹配项后运行此代码来解决此问题。
第三,如果没有匹配项,则不要循环回到 while 循环的开头,而是使用 再次调用该函数logging()
。这将启动函数的新迭代,并且由于它永远不会返回任何内容,因此您将陷入无限递归。相反,我们循环回到 while 函数的开头。
在我们达到尝试 3 之后,我添加了一条消息和一个返回值。logging()
现在返回True
,如果用户在 3 次尝试内输入了正确的用户/通行证组合,False
否则。
示例代码如下。
def logging():
# Set attempt number to 0
atmptcount = 0
# Keep asking until max number of attempts is reached
while atmptcount <= 3:
# Prompt user for input
usr = input('Please enter your username: ')
pas = input('Please enter your password: ')
# Check through login file
for line in login:
log = line.split(',')
# If details are correct, tell the user and return True
if usr == log[0] and pas == log[1]:
print('correct')
return True
# If we reached the end of the login file and nothing matched, increase
# attempts by 1 and inform the user.
atmptcount = atmptcount + 1
print('Sorry you have entered your details incorrectly, please try again')
# If the user has reached the max attempts, inform them and return False
print('Reached max number of attempts')
return False
logging()
推荐阅读
- javascript - 验证表单 ng-click 功能不起作用后加载页面
- node.js - 授权中间件功能
- kubernetes - Kubernetes kubectl 不使用 prune 选项修剪资源
- javascript - 使用 Mongoose for Node.js 将 JSON 推送到 Mongo 文档的子数组中
- android - 物体检测和计算相机和物体之间的距离
- javascript - 在 array.forEach 函数语句中使用 if 语句来选择对象数组中的子对象
- r - 按组在多个列上执行多个函数,并创建信息丰富的列名
- javascript - 我想通过jq获取ng-show的值,但不是我预期的结果
- gnuplot - gnuplot 的问题 - 时间戳数据映射到 xrange
- python-2.7 - 使用 witdraw() 隐藏弹出框会导致窗口大小不合适