我不确定为什么此代码无法正常工作。我有错误TypeError:'int'对象不可迭代。我需要代码来检查两个不同列表中的用户名和密码,如果用户名和密码与列表中的点匹配并且正确,则用户为“授予访问权限。”
#Part 1: Opening the files and grabbing data
filename1 = "c:\\Users\\Anna Hamelin\\Documents\\Python Scripts\\SourceCode\\Project2\\usernames.txt"
file = open(filename1, "r")
#Usernames
users = file.read()
usernameslist = [line.strip() for line in open("c:\\Users\\Anna Hamelin\\Documents\\Python Scripts\\SourceCode\\Project2\\usernames.txt")]
print(users) #Check file
print(usernameslist) #Check usernames list
filename2 = "c:\\Users\\Anna Hamelin\\Documents\\Python Scripts\\SourceCode\\Project2\\passwords.txt"
file = open(filename2, "r")
#Passwords
passwords = file.read()
passwordslist = [line.strip() for line in open("c:\\Users\\Anna Hamelin\\Documents\\Python Scripts\\SourceCode\\Project2\\passwords.txt")]
print(passwords) #Check file
print(passwordslist) #Check passwords list
#Compile the usernames and passwords lists for easy checking
compiled_list = list(zip(usernameslist,passwordslist))
print(compiled_list)
#Scores
filename3 = "c:\\Users\\Anna Hamelin\\Documents\\Python Scripts\\SourceCode\\Project2\\scores.txt"
file = open(filename3, "r")
scores = file.read()
scoreslist = [line.strip() for line in open("c:\\Users\\Anna Hamelin\\Documents\\Python Scripts\\SourceCode\\Project2\\scores.txt")]
print(scores) #Check file
print(scoreslist) #Check scores
def login():
username = input("Please enter your username: ")
password = input("Please enter your password: ")
for i in range(len(usernameslist)):
if username == i and password == [i]:
print("Access granted!")
else:
print("Incorrect Login credentials, please try again.")
login()
答案 0 :(得分:2)
问题出在login()
中,您正在使用i
作为其内部的迭代器。
def login():
username = input("Please enter your username: ")
password = input("Please enter your password: ")
for i in [usernameslist]:
if username == [i]:
for j in [passwordslist]:
if password == [j]:
return "Access granted!"
else:
return "Incorrect Login credentials, please try again."
else:
return "Incorrect Login credentials, please try again."
以上内容应找到密码并与您的逻辑配合使用。 但是,您是否不应该使用特定的用户名作为密码?这是在检查用户名和密码是否可用,而不是密码是否与用户名匹配。当您分别遍历浏览密码和用户名时,您只需检查某人是否具有密码和某人是否具有用户名(是否是同一个人)。如果是这样,请替换为:
def login():
username = input("Please enter your username: ")
password = input("Please enter your password: ")
for i in range(len(usernameslist)):
if username == i and password == j:
return "Access granted!"
else:
return "Incorrect Login credentials, please try again."
请确保在两个列表中用户名和密码的顺序相同。或者,我建议存储如下所示的 2D列表:
list = [["Annie","password1"],["bob","wordpass39"]]
,其中第一项是用户名,第二项是密码。
编辑:,使用固定的login()
功能,您现在应该这样做:
def login():
username = input("Please enter your username: ")
password = input("Please enter your password: ")
for i in range(len(usernameslist)):
if username == i and password == i:
print("Access granted!")
else:
print("Incorrect Login credentials, please try again.")