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

Using logical operators with If statements won't output what is expected

I’m starting to learn Python and wrote this:


num1 = int(input('First number '))
num2 = int(input('second number '))
num3 = int(input('third number '))

if num1 > (num2 and num3):
    print(f'{num1:2} is bigger')
    if num2 > num3:
        print(f'{num3:2} is smaller')
    if num3 > num2:
        print(f'{num2:2} is smaller')

if num2 > (num1 and num3):
    print(f'{num2:2} is bigger')
    if num1 > num3:
        print(f'{num3:2} is smaller')
    if num3 > num1:
        print(f'{num1:2} is smaller')
    

if num3 > (num1 and num2):
    print(f'{num3:2} is bigger')
    if num1 > num2:
        print(f'{num2:2} is smaller')
    if num2 > num1:
        print(f'{num1:2} is smaller')

If I enter "5" for the first number "4" for the second and "2" for the third
it outputs:

"5 is bigger
 2 is smaller
 4 is bigger
 2 is smaller"

Why does he reads the line with the false condition statment?

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

What did I miss?

Also another way to write it would be:

"if num2 > (num1 and num3) and (num1 < num3):
    #print(f'{num2:2} is bigger and {num1:2} is smaller')"

but also didn’t work.

Thanks everyone.

>Solution :

num1 > (num2 and num3)

That doesn’t work how you think it does, you need something like:

num1 > num2 and num1 > num3

# Or if there's lots of them:
num1 > max(num2, num3, num4, num5)

Your current method first calculates num2 and num3 by giving you num2 if it’s false (see below), or num3 otherwise. So 3 > (4 and 2) is the same as 3 > 2, because 4 and 2 is 2. The following transcript illustrates this:

>>> print(0 and 99)
0
>>> print(1 and 99)
99
>>> print(2 and 99)
99
>>> print(-1 and 99)
99

Basically, numbers are considered false if they’re zero, hence the output shown above.


As an aside, you may also want to think about what will happen if two or more of the numbers are equal.

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