首页 > 解决方案 > 登录认证系统

问题描述

我正在为我提议的一个学校项目制作一个 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()

标签: pythonpython-3.xcsvfor-loopinput

解决方案


这里的逻辑有点缺陷,我已经稍微纠正了——不过你的思路是对的!

首先,您要求用户在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()

推荐阅读