Python Forum

Full Version: I'm getting a wrong answer don't know where the bug is
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I've written a program that inputs three integers and calls functions to determine the smallest and the largest of the three. But sometimes my program gives the wrong answer. I have written this program in C# the same way and there is no bugs.

In this Python version if I enter the integers 1, 3, and 6 my program reports that the smallest is 1 and the largest is 3.

Here is what I've currently got:

def smallest(a, b, c):
    smallest = a

    if b < smallest:
        smallest = b
    elif c < smallest:
        smallest = c

    return smallest

def largest(a, b, c):
    largest = a

    if b > largest:
        largest = b
    elif c > largest:
        largest = c

    return largest

x = int(input("Enter first number:"))
y = int(input("Enter second number:"))
z = int(input("Enter third number:"))

print()

smallest_integer = smallest(x, y, z)
largest_integer = largest(x, y, z)

print("The smallest is", smallest_integer)
print("The largest is", largest_integer)
maybe this

def smallest(a, b, c):
    smallest = a
 
    if b < smallest:
        smallest = b
    elif c < smallest and b > c:
        smallest = c
 
    return smallest
 
def largest(a, b, c):
    largest = a
 
    if b > largest and b > c:
        largest = b
    elif c > largest and b < c:
        largest = c
 
    return largest
 
x = int(input("Enter first number:"))
y = int(input("Enter second number:"))
z = int(input("Enter third number:"))
 
print()
 
smallest_integer = smallest(x, y, z)
largest_integer = largest(x, y, z)
 
print("The smallest is", smallest_integer)
print("The largest is", largest_integer)
I found a solution. You can't use elif. You have to only use if statements. As soon as Python finds the condition in the if statement to be true, it will skip the remaining elif statement.
when entering the integers 1, 3, and 6 the program reports that the smallest is 1 and the largest is 3 because in the function largest the if checks for 3 being larger than 1 which it is so it sets largest to 3, because the following condition is a elif this doesn't happen because the first if was true. if the second elif was an if it would calculate the largest as 6.
Why not using min and max?
Lesser code > lesser bugs.

def smallest(a, b, c):
    return min(a, b, c)


def largest(a, b, c):
    return max(a, b, c)