2

嗨,我对如何做我想做的事情感到完全困惑,我基本上是在检查一个文件,它在这个例子中包含两个单词,即用户的用户名和密码。

text = open("Accounts.dat", 'w')
text.writelines("the username")
text.writelines("\n")
text.writelines("the password")
text.close()

username = input("Enter username: ")
password = input("Enter password: ")
data = open("Accounts.dat").read()
if username and password in data:
  print("works")
else:
  print("doesn't work")
data.close()

这段代码在某些方面确实有效,比如如果我只输入正确的用户名,而它打印的密码没有任何内容(“有效”),但如果我在用户名和密码中没有输入任何内容(“无效”),那么如果我只是输入正确的密码,而用户名什么也没有,它不起作用。

我需要它,所以它只在用户名和密码都正确时打印(“有效”)。

4

1 回答 1

3

if username and password in data:应该

if username in data and password in data:

当你这样做if username and password in data:时,python 会解释它的方式是:

if (username) and (password in data):

也就是说,检查 if usernameisTrue并检查 if passwordis indata

于 2013-05-15T21:28:57.703 回答