Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

extreme Noob needs short review on "if" and "!="

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 🙂

>Solution :

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?

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading