为什么此 if/else 语句中的这些布尔表达式未按预期计算?

Why are these boolean expressions in this if/else statement not evaluating as expected?

提问人:boxerbobby 提问时间:11/9/2021 最后编辑:nbrooksboxerbobby 更新时间:11/9/2021 访问量:61

问:

你能看一下,告诉我代码有什么问题吗?

e = eval(input('enter 1 '))
f = eval(input('enter 3 '))

if e != 1 and f != 3:
    print('you got it wrong!')
else:
    print("correct")

所以这里的问题是,如果我正确输入 1 个数字中的 2 个,它说它是正确的,但它不应该,因为我有一个“and”运算符?

当然,我可以将代码更改为这样可以正常工作的内容:

if e == 1 and f == 3:
    print('correct')
else:
    print("you got it wrong!")

但另一方面,我想知道我做错了什么? 谢谢:)

python-3.x 布尔逻辑

评论

0赞 jasonharper 11/9/2021
e != 1意思是“e是错误的”。 表示“f 是错误的”。你的陈述条件是“e 是错误的,f 是错误的”。f != 3if
2赞 Mateen Ulhaq 11/9/2021
brilliant.org/wiki/de-morgans-laws

答:

3赞 U13-Forward 11/9/2021 #1

if e != 1 and f != 3:意思是如果错了也是错的。但正如你所提到的,你输入了一个正确的,然后语句就没有通过,因为其中一个仍然是正确的。efand

你需要:or

if e != 1 or f != 3:
    print('you got it wrong!')
else:
    print("correct")

顺便说一句,我建议你用代替(因为这是不好的做法,而且你正在转换为整数):intevaleval

e = int(input('enter 1 '))
f = int(input('enter 3 '))

阅读:为什么使用“eval”是一种不好的做法?

1赞 wjandrea 11/9/2021 #2

逻辑是错误的。使用德摩根定律

x AND y反转→ →x NAND yNOT x OR NOT y

哪里代表和代表xe == 1yf == 3