2 回答

TA貢獻(xiàn)1725條經(jīng)驗(yàn) 獲得超8個(gè)贊
我建議稍微重新格式化代碼,以便更容易找到用戶名是否存在以及密碼是否正確。
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貢獻(xiàn)1820條經(jīng)驗(yàn) 獲得超9個(gè)贊
你在循環(huán)中有一個(gè)邏輯錯(cuò)誤 - 你似乎將文本文件中的每一行與提供的用戶名和密碼進(jìn)行比較,如果它們不匹配則說明錯(cuò)誤 - 忽略用戶可能不在第一行的事實(shí)文件。僅當(dāng)您遍歷整個(gè)文件但未找到用戶,或找到用戶但密碼不匹配時(shí),才會(huì)顯示該錯(cuò)誤。
另外,我認(rèn)為您根本不需要內(nèi)部循環(huán),您聲明了 x 和 y 但不使用它們,您是否嘗試過打印它們并檢查它們包含的內(nèi)容?
無論如何,這是我認(rèn)為循環(huán)應(yīng)該是什么樣子的輪廓
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.")
添加回答
舉報(bào)