python if 条件 "and"关键字问题

标签 python string if-statement

我只是想调用这段代码

uname=""
passwd="jhj"
if uname =="":print "uname"
if passwd=="":print "passwd"
if not uname and passwd:
    print "either"

输出是:

uname
either

它不应该是“uname”吗?我该如何解决这个问题?

最佳答案

简单的修复是

if not uname and not passwd:

因为它的计算结果为

if (not uname) and (not passwd):

if not (uname or passwd):

但是如果既没有提供 uname 也没有提供 password(它将打印所有三个),这将无法像预期的那样工作。

您可以更改此构造的逻辑,其中只执行一个 print:

uname = ""
passwd = "jhj"

if not (uname or passwd):
    print "either"
elif not uname:
    print "uname"
elif not passwd:
    print "passwd"

关于python if 条件 "and"关键字问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10204968/

相关文章:

python - 'int' object is not callable 错误在 python 中

python - 如何重现 Ridge(normalize=True) 的行为?

python - 使用 matplotlib + tkinter 在图表的 x 轴上设置日期

string - 在 Delphi 中查找和计算字符串中的单词?

Java if 语句不起作用

javascript - 基本的 If else 语句在 JavaScript 中不起作用

python - 这本字典中的 for 循环到底是如何工作的?

java 我可以在一行中创建一个定义为空的字符串吗?

java - java中单词之间添加空格并使每个单词除了第一个小写之外

java - 根据条件禁用/启用语句的方法或模式?