python - 为什么这两个代码片段不能正常工作?
问题描述
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
==
jim
hello
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!
""")
即使在此之后,我也没有看到我的代码按预期运行。
解决方案
我会使用字典在循环之外建立用户名和密码。然后,您可以根据 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
推荐阅读
- linux - Logstash 在 Ubuntu 中没有显示任何输出
- google-apps-script - 谷歌脚本 DriveApp.getFolders().hasNext() 错误
- javascript - 同时更改范围滑块和输入框的值
- javascript - 谷歌翻译、必应翻译等网站如何工作?
- r - 为什么在没有值的情况下会收到一条错误消息,指示无限值?
- mysql - MySQL:具有范围和顺序的查询索引
- javascript - 数组推送 12 个对象而不是 4 个。一些属性留空
- python - 为什么我的while循环没有进入里面的if语句?
- javascript - cors 没有将我的 cookie 设置为浏览器,但在邮递员中工作正常
- c# - 使用 ProgressBar 监控 SQL 查询的执行进度,如果 sql 表的 field_id 增加 1 则更新进度条百分比