首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >登录认证系统

问登录认证系统
EN

Stack Overflow用户
提问于 2020-01-28 21:10:19
回答 1查看 91关注 0票数 1

我正在为我提议的一个学校项目做一个python登录系统,我有一个逻辑错误,我找不到。程序应该允许三次登录尝试,当你登录时应该显示“正确”,但程序运行,当你输入正确的用户名和密码时,它会打印“你输入了错误的密码”并循环程序,然后当你输入任何值时,它就会停止程序,什么也不会出现。你能帮我找出逻辑错误吗?我很乐意解释任何功能的作用:)

代码语言:javascript
复制
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()
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-01-28 21:19:25

这里的逻辑有一点缺陷,我稍微纠正了一下--尽管你说对了!

首先,在while循环之外请求用户输入。这意味着每次循环返回时,用户不会再有机会输入新的细节。

其次,对于elif语句,每当user/pass与login列表中的任何一行不匹配时,都会运行该语句。我们只在检查完整个文件后才运行此代码,但没有找到匹配项,从而解决了这个问题。

第三,不是在没有匹配的情况下返回到while循环的开头,而是使用logging()再次调用该函数。这将启动函数的新迭代,并且由于它永远不会返回任何内容,因此您将陷入无限递归。相反,我们循环回到while函数的开头。

在到达尝试3之后,我添加了一条消息和一个返回值。现在,如果用户在3次尝试中输入了正确的用户名/通行证组合,则logging()返回True,否则返回False。

示例代码如下。

代码语言:javascript
复制
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()
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59949536

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档