highest number finding code is having errors because of try loop or while loop

Viewed 44
  1. This code is supposed to find the biggest number.
  2. When I plug in (200, 4, 100) in order, it says that 4 is the biggest number.
  3. When I plug in numbers of similar size, it has no problem.
  4. I feel like this is due to my lack of looping knowledge.
  5. Can someone teach me what's the issue? (student still learning)
def num_max(num1, num2, num3):
    if num1 >= num2 and num1 >= num3:
        return(num1)
    elif num2 >= num1 and num2 >= num3:
        return(num2)
    else:
        return(num3)


while 1:
    num1 = input("#1: ")
    try:
        in1 = int(num1)
        break
    except:
        print("Invalid: Try again")


while 1:
    num2 = input("#2: ")
    try:
        in2 = int(num2)
        break
    except:
        print("Invalid: Try again")


while 1:
    num3 = input("#3: ")
    try:
        in3 = int(num3)
        break
    except:
        print("Invalid: Try again")


print("The biggest number you entered is the following:  ")
print(num_max(num1, num2, num3))
2 Answers

You don' need a while look for inputs. This is an additional overhead and slows down your program. You should also pass your function the ints themselves not the strings.

This should work:

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


try:
    num1 = input("#1: ")
    num2 = input("#2: ")
    num3 = input("#3: ")

    in1 = int(num1)
    in2 = int(num2)
    in3 = int(num3)
except:
    print("Invalid: Try again")

print(num_max(in1, in2, in3))

This is because you are using the string numvariables for the function, try sending just the int variables in, and when you compare strings, 4 is greater than 200.

Change this line:

print(num_max(num1, num2, num3))

whit this one:

print(num_max(in1, in2, in3))
Related