用户名/密码程序的打印语句不正确

时间:2013-12-17 19:21:24

标签: python python-3.x

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下发出的语句。谁知道我做错了什么?

2 个答案:

答案 0 :(得分:2)

您完全根据密码文件的第一行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")

答案 1 :(得分:0)

else语句返回false,这意味着它在第一次失败的比较时退出函数。

你需要做的是简单地使用if,如果没有返回true,则返回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