【问题标题】:Incorrect print statement for username/password program用户名/密码程序的打印语句不正确
【发布时间】:2013-12-17 19:21:24
【问题描述】:
def login():
    UserName = input("Please enter your username: ")
    passw = input("Please enter your password: ")
    check(UserName, passw)
    if check(UserName, passw) == True:
        print("Thank you for logging in. Please enjoy these lyrics")
    else:
        print("Sorry, either your username or password is incorrect")

def check(UserName, passw):
    pword = {}
    for line in open('unames_passwords.txt','r'):
        user, password = line.split()
        pword[user] = password
        if user == UserName and password == passw:
            return True
        else:
            return False


def main():
    login()

我当前的代码遇到的问题是,如果我输入文件中包含的名字和密码,它会打印 if True, print 语句,但如果我在文件中输入任何其他名称和密码同一个文件,它总是打印在 else 下发出的语句。有谁知道我做错了什么?

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    您仅根据密码文件的第一行从check()返回。如果第一个密码不匹配,则立即返回False。

    将return False移出循环,使其仅在扫描整个文件时执行:

    def check(UserName, passw):
        for line in open('unames_passwords.txt','r'):
            user, password = line.split()
            if user == UserName and password == passw:
                return True
    
        return False
    

    我在这里删除了pword 字典处理;您的代码实际上并没有使用它。

    您可能希望避免每次登录两次调用check(),并且您不必测试== True; if 声明已经为您测试:

    def login():
        UserName = input("Please enter your username: ")
        passw = input("Please enter your password: ")
        if check(UserName, passw):
            print("Thank you for logging in. Please enjoy these lyrics")
        else:
            print("Sorry, either your username or password is incorrect")
    

    【讨论】:

    • 效果很好。我花了一点时间才意识到为什么要这样做。非常感谢
    【解决方案2】:

    else 语句返回 false,表示在第一次比较失败时退出函数。

    你需要做的就是简单的加上if,在for的末尾如果没有return true,就return false。

    比如:

    for line in open('unames_passwords.txt','r'):
            user, password = line.split()
            pword[user] = password
            if user == UserName and password == passw:
                return True
    return False
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-08
      • 2016-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-17
      相关资源
      最近更新 更多