Search code examples
pythonif-statementcomparison

What is the detailed difference between two Python codes, both written to find the largest number among three inputs


How can I understand detailed difference between below two codes written to find the largest number among three numbers.

Code1:

def max_num(num1, num2, num3):
    if num1 >= num2 and num1 >= num3:
        return num1
    elif num2 >= num1 and num2 >= num3
        return num2
    else:
        return num3

Code2:

def max_num(num1, num2, num3):
    if num1 > num2 and num1 > num3:
        return num1
    elif num2 > num1 and num2 > num3
        return num2
    else:
        return num3

Solution

  • EDIT: Code2 could erroneously return num3 as max if num1 == num2, ie in [6, 6, 5].

    The main difference, as commented above, is the use of "greater than" vs "greater or equal". I think the only place this would matter is when you have multiple values in the list which are equal, in which case Code2 would return the first instance, whereas Code3 would return the last.