Jbthomp Jbthomp - 8 months ago 27
Python Question

If statement not evaluating all the conditions and executing anyway

Ok so I am new to python and trying to learn how to code. I ran into an issue today that I don't understand. So this code executes as expected and prints the largest of the three numbers no matter what position the largest number is.

if num1 >= num2 and num3:
print(num1, 'Is the greatest number!')

elif num2 >= num3 and num1:
print(num2, 'Is the greatest number!')

print(num3, 'Is the greatest number')

But if i change the elif statement to this:

elif num2 >= num1 and num3:
print(num2, 'Is the greatest number!')

Even if num3 is the largest the else statement will not execute and it will display the larger number of num1 or num2.


The problem here is a misunderstanding in the way the keyword and works.

In python, and is used to separate two complete logical statements: cond1 and cond2. It first checks cond1. If cond1 is True, it moves on to check cond2. If cond2 is also True, then the whole statement evaluates to True.

When you do if num1 >= num2 and num3, you are actually asking python if the following is True:

  1. num1 >= num2
  2. num3 exists and is not empty

It is not checking if num1 >= num2 and num1 >= num3.

So if num1 = 2, num2 = 1, num3 = 3, your conditional will still return True for if num1 >= num2 and num3.

The same concept applies to your problem conditional.