Search code examples
pythonif-statementnumbers

Python if elif not getting expected results


In Python 3. It reads correctly the 1st and the 2nd variable when they have the highest value. But the 3rd is not.

n1 = int(input("1st Number:\n"))
n2 = int(input("2nd Number:\n"))
n3 = int(input("3rd Number:\n"))

if n1 > n2 and n3:
    print(f'\033[1;31m{n1}\033[m')
elif n2 > n1 and n3:
    print(f'\033[4;32m{n2}\033[m')
elif n3 > n1 and n2:
    print(f'\033[33m{n3}\033[m') #When is the highest value it's not considered.

Solution

  • In your case, the condition n1 > n2 will be True if n1 is greater than n2, and the condition n3 will always be True because n3 is an integer. As all non-zero integers are considered True in a boolean context, the same logic applies for the second elif i.e n2 > n1. So you need to change the condition like this.

    n1 = int(input("1st Number:\n"))
    n2 = int(input("2nd Number:\n"))
    n3 = int(input("3rd Number:\n"))
    
    if n1 > n2 and n1 > n3:
        print(f'\033[1;31m{n1}\033[m')
    elif n2 > n1 and n2 > n3:
        print(f'\033[4;32m{n2}\033[m')
    elif n3 > n1 and n3 > n2:
        print(f'\033[33m{n3}\033[m') #When is the highest value it's not considered.