我有一个包含多个(用户名,密码)对的.txt文件,如下所示:
jack : ace
我写了一个代码让用户输入他们的名字和密码,并在数据库中验证这些:
data={}
with open("user.txt", "r") as f:
for line in f.readlines():
name,password = line.strip().split(":")
data[str(name)]=str(password)
counter = 3
while True:
print "Log In"
username = raw_input ("Username : ").lower()
pword = raw_input ("Password : ").lower()
for username in data:
if data[name] == password :
print "Welcome Misterrr"
break
if data[username] != password :
print "Boo Boo .Suckerr!!"
counter = counter - 1
if counter == 0:
print "Limit try reached already.Bye!"
break
问题是,在用户输入用户名和密码后,代码不会跟随循环,它不会中断,似乎它与用户输入值不匹配字典值。我该如何解决这个问题?
答案 0 :(得分:0)
您有两个主要问题:
首先,您并未真正使用用户输入的值...:当您输入for循环时,username
会被覆盖,并且在创建后永远不会调用pword
。
其次,登录成功时使用的break
只会突破for循环,而不是while循环。
修正逻辑:
counter = 3
done = False
while done is False:
print "Log In"
username = raw_input ("Username : ").lower()
pword = raw_input ("Password : ").lower()
# Check if the user exists in the database or not
if username not in data.keys():
print "Never seen this name before!..."
counter = counter - 1
else:
# Check if the input password matches the database password
if data[username] == pword :
print "Welcome Misterrr"
done = True
else:
print "Boo Boo .Suckerr!!"
counter = counter - 1
if counter == 0:
print "Limit try reached already.Bye!"
break