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

Time:11-09

Could you please take a short look and tell me what's wrong with the code?

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

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

So the problem here is if I enter 1 of 2 numbers correct, it says that it is correct but it shouldn't because I have an "and" operator ?

Of course I could change the code to something like this which would work fine:

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

But on the other side I would like to understand what I'm doing wrong? Thanks :)

CodePudding user response:

if e != 1 and f != 3: means if e is wrong and f is also wrong. But as you mentioned, you entered one right, then the and statement doesn't get through, since one of them are still right.

You need or:

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

Btw, I recommend you to use int instead of eval (since eval is bad practice, and you are converting to an integer):

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

Read: Why is using 'eval' a bad practice?

CodePudding user response:

The logic is wrong. Use De Morgan's laws:

x AND y invert → x NAND yNOT x OR NOT y

where x stands for e == 1 and y stands for f == 3

  • Related