Python if elif not getting expected results

Question:

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'33[1;31m{n1}33[m')
elif n2 > n1 and n3:
    print(f'33[4;32m{n2}33[m')
elif n3 > n1 and n2:
    print(f'33[33m{n3}33[m') #When is the highest value it's not considered.

Answers:

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'33[1;31m{n1}33[m')
elif n2 > n1 and n2 > n3:
    print(f'33[4;32m{n2}33[m')
elif n3 > n1 and n3 > n2:
    print(f'33[33m{n3}33[m') #When is the highest value it's not considered.
Answered By: Always Sunny
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.