2 回答
TA贡献1725条经验 获得超7个赞
我建议稍微重新格式化代码,以便更容易找到用户名是否存在以及密码是否正确。
import time
#User input of username and password
user_name = input("Username:\n")
user_pass = input("Password: \n")
#Opening document
with open("user.txt", "r+", encoding = "utf-8-sig") as f:
new_lines = []
for line in f:
new_line = line.strip()
new_lines.append(new_line.split(","))
usernames = [acc[0] for acc in new_lines]
pws = [acc[1] for acc in new_lines]
while True:
if user_name not in usernames:
print("Error! Username does not exist.")
user_name = input("Username:\n")
user_pass = input("Password: \n")
else:
pw_index = usernames.index(user_name)
if user_pass != pws[pw_index]:
print("Error! Incorrect password.")
user_name = input("Username:\n")
user_pass = input("Password: \n")
else:
print("Welcome back!")
break
#User options to choose from
user_choice = input("""\nPlease select one of the following options:
\nr - register user
\na - add task
\nva - view all tasks
\nvm - view my tasks
\ne - exit
\nAnswer: """)
TA贡献1820条经验 获得超9个赞
你在循环中有一个逻辑错误 - 你似乎将文本文件中的每一行与提供的用户名和密码进行比较,如果它们不匹配则说明错误 - 忽略用户可能不在第一行的事实文件。仅当您遍历整个文件但未找到用户,或找到用户但密码不匹配时,才会显示该错误。
另外,我认为您根本不需要内部循环,您声明了 x 和 y 但不使用它们,您是否尝试过打印它们并检查它们包含的内容?
无论如何,这是我认为循环应该是什么样子的轮廓
found = False
for current_user, current_password in new_lines:
if current_user == user_name:
if current_password == user_pass:
print("Welcome back!")
found = True
else:
print("Error! Incorrect password")
break
if not found:
print("Error! Username does not exist.")
添加回答
举报