[Python] Help with Exceptions?

Debugging

I tried to make a simple calculator, but it's throwing an error when I input an alphabet character when it expects an integer.

I used pass on Except because I don't want it to throw back any message, I just want it to keep on looping until it gets an integer.

I think the problem is I'm trying it on two elements (num1, num2) because this works if I only use it with a function returning 1 element.

def get_num(computanta, computantb):
    try:
        num1 = int(input(f"\nEnter {computanta}: "))
        num2 = int(input(f"Enter {computantb}: "))
        return num1, num2
    except ValueError:
        pass

def addition(num1, num2):
    return num1 + num2

def subtraction(num1, num2):
    return num1 - num2

def multiplication(num1, num2):
    return num1 * num2

def division(num1, num2):
    return num1 / num2

print("\nB A S I C   C A L C U L A T O R")
while True:
    print("\nSelect An Operator")
    operator = input("1 - Addition\n2 - Subtraction\n3 - Multiplication\n4 - Division\n\n")

    if operator == "1":
        computanta = computantb = "addend"
        num1, num2 = get_num(computanta, computantb)
        print(f"\nThe sum of {num1} and {num2} is {addition(num1, num2)}")

    elif operator == "2":
        computanta = "minuend"
        computantb = "subtrahend"
        num1, num2 = get_num(computanta, computantb)
        print(f"\nThe difference of {num1} and {num2} is {subtraction(num1, num2)}")

    elif operator =="3":
        computanta = computantb = "factor"
        num1, num2 = get_num(computanta, computantb)
        print(f"\nThe product of {num1} and {num2} is {multiplication(num1, num2)}")

    elif operator =="4":
        computanta = "dividend"
        computantb = "divisor"
        num1, num2 = get_num(computanta, computantb)
        print(f"\nThe quotient of {num1} and {num2} is {division(num1, num2)}")

    else:
        print("\nPlease Select A Valid Operation")

What went wrong there?

Thanks

Posted Aug 31, 2025, 12:18 AM UTC

22
Loading comments…