【问题标题】:python 'and' boolean operatorpython 'and' 布尔运算符
【发布时间】:2013-05-15 21:27:57
【问题描述】:

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

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()

此代码在某些方面确实有效,例如,如果我只输入正确的用户名,而它打印的密码没有任何内容(“有效”),但如果我在用户名和密码中没有输入任何内容,它就会打印(“不起作用”) ,那么如果我只输入正确的密码,而没有输入用户名,它就不起作用了。

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

【问题讨论】:

  • 这不是一个好的方案。例如,您可以再次输入用户名作为密码。

标签: python boolean and-operator


【解决方案1】:

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):

也就是说,检查username 是否为True 并检查password 是否在data

【讨论】:

  • 这种语言很像英语,所以很容易犯错。
  • 不仅仅是username 不是None。空字符串也将评估为False。更多的是username.__bool__True
  • @karthikr 确实有效,但现在,当它没有打印任何内容(“有效”)时,当只有正确的密码时它会打印(“有效”),当只有正确的用户名时它打印(“有效”),如果用户名正确且密码错误,则打印(“不起作用”),正确的密码和错误的用户名也是如此
  • 你可以这样做if username and password and username in data and password in data
猜你喜欢
  • 2013-06-06
  • 2015-11-18
  • 1970-01-01
  • 1970-01-01
  • 2011-07-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-20
相关资源
最近更新 更多