首页 > 解决方案 > 为什么这两个代码片段不能正常工作?

问题描述

data.txt文件如下所示:

jim@gmail.com: hello123
malik@gmail.com: helloworld
jim24@gmail.com: hell123

以下代码从data.txt文件中提取信息,并根据输入的用户名和密码使用它来拒绝或授予用户访问权限。

current_attempts = 0
total_attempts = 3
data_file = open('data.txt', 'r')
read_datafile = data_file.read()
while current_attempts < total_attempts:
    username = input("Enter Email: ")
    password = input("Enter Password: ")

    if username in read_datafile and password in read_datafile:
        print(f"""Access Granted. Welcome {username}!
""")
        break

    elif username not in read_datafile and password not in read_datafile:
        current_attempts += 1
        print(f"""Access Denied. You have {total_attempts - current_attempts} chances left!
""")

上述代码仅检查输入的用户名和密码是否在data.txt文件中,但不会比较:和之间的区别。例如,如果我只输入用户名和密码,那么用户也被授予访问权限。为避免这种情况,我已经准备了另一个代码片段可以帮助比较两个数据,并且仅在两个数据完全匹配时授予用户访问权限:in==jimhello

for line in data_file.readlines():
    break_line = line.index(':')
    _email = line[:break_line]
    _password = line[(break_line + 2):len(line)]

当我合并这两个片段时,我得到了这个:

current_attempts = 0
total_attempts = 3
data_file = open('data.txt', 'r')
while current_attempts < total_attempts:
    username = input("Enter Email: ")
    password = input("Enter Password: ")

    for line in data_file.readlines():
        break_line = line.index(':')
        _email = line[:break_line]
        _password = line[(break_line + 2):len(line)]

        if username == _email and password == _password:
            print(f"""Access Granted. Welcome {username}!
""")
            break

        elif username != _email and password != _password:
            current_attempts += 1
            print(f"""Access Denied. You have {total_attempts - current_attempts} chances left!
""")

即使在此之后,我也没有看到我的代码按预期运行。

标签: python

解决方案


我会使用字典在循环之外建立用户名和密码。然后,您可以根据 dict 检查用户名和密码并计算失败的尝试次数。

with open('data.txt', 'r') as f:
    authdict = {}
    for line in f:
        username, password = line.split(': ')
        authdict[username.strip()] = password.strip()

然后

while current_attempts < total_attempts:
    username = input("Enter Email: ")
    password = input("Enter Password: ")
    if authdict.get(username) == password:
        # you are authorized, break loop
        break
    # otherwise do what you need to do for unauthorized

推荐阅读