-1

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!')

    else:
        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.

Jbthomp
  • 11
  • 3
  • Try running with `num1 = 2`, `num2 = 1` and `num3 = 10`, the first snippet of code won't work. It will print "(2, 'Is the greatest number!')". – petabyte Jul 07 '16 at 21:44

2 Answers2

2

Your first version works purely by coincidence. You need to do

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

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

else:
    print(num3, 'Is the greatest number')

Although, this will still print wrong info if any of the numbers are equal

Falmarri
  • 47,727
  • 41
  • 151
  • 191
1

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 0 (since it's a number)

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.

xgord
  • 4,606
  • 6
  • 30
  • 51