using try/except & while loop for calculator in python

678 Views Asked by At

I am trying to create a calculator and use defensive programming to avoid unexpected events and user inputs.

I included a try/except block for user input & for zero division.

When I input the division operator to calculate a zero division, my loop is not taking me back to input the number. It's taking me back to input the operator.

I also, struggle to re`loop the calculator for the user to start a new calculation.

Many thanks for the help.

while True:

    try:
        
        num1 = float(input("Please enter a number:"))
        num2 = float(input("Please enter another number: "))
        break
        
    except ValueError:
        print("Wrong key entered. Please key in a number")

operator = input("Please enter the operator (+, -, *, /): ")        
while True: 
        
    if operator == "+":
        calculation = num1 + num2
        entry = ("{} + {} = {}".format(num1,num2,calculation))  
        print(entry) 
        
    elif operator == "-":
        calculation = num1 - num2
        entry = ("{} - {} = {}".format(num1,num2,calculation)) 
        print(entry)
        
    elif operator == "*":
        calculation = num1 * num2
        entry = ("{} * {} = {}".format(num1,num2, calculation)) 
        print(entry)   
        
    elif operator == "/":
        try:    
            calculation = num1 / num2
            entry = ("{} / {} = {}".format(num1, num2, calculation))
            print(entry)
            break
            
        except ZeroDivisionError:
            print("You cannot divide by zero. Please try again!") 
    
    choice = input("Continue - Y / No - N: ")
    if choice == "N":
            break
    else:   
        print("You have not entered a valid operator, please try again.")
3

There are 3 best solutions below

0
Barmar On BEST ANSWER

Put the calculation code inside your first while True: loop, not a separate loop. Then you can go back to the prompts for the numbers when there's an arithmetic error or the user says to continue.

while True:
    try:
        num1 = float(input("Please enter a number:"))
        num2 = float(input("Please enter another number: "))

        operator = input("Please enter the operator (+, -, *, /): ")        

        if operator == "+":
            calculation = num1 + num2
            entry = ("{} + {} = {}".format(num1,num2,calculation))  
            print(entry) 

        elif operator == "-":
            calculation = num1 - num2
            entry = ("{} - {} = {}".format(num1,num2,calculation)) 
            print(entry)

        elif operator == "*":
            calculation = num1 * num2
            entry = ("{} * {} = {}".format(num1,num2, calculation)) 
            print(entry)   

        elif operator == "/":
            calculation = num1 / num2
            entry = ("{} / {} = {}".format(num1, num2, calculation))
            print(entry)

        else:   
            print("You have not entered a valid operator, please try again.")
            continue

        choice = input("Continue - Y / No - N: ")
        if choice == "N":
            break

    except ValueError:
        print("Wrong key entered. Please key in a number")

    except ZeroDivisionError:
        print("You cannot divide by zero. Please try again!") 
0
KSs On

If you want to loop the whole calculator and be able to control the whole process, you can move operations to methods and add them into one while loop

def choose_numbers():
    try:
        num1 = float(input("Please enter a number:"))
        num2 = float(input("Please enter another number: "))
        return {"num1":num1,"num2":num2}
    except ValueError:
        print("Wrong key entered. Please key in a number")

def choose_operator(num1, num2):

    operator = input("Please enter the operator (+, -, *, /): ")

    if operator == "+":
        calculation = num1 + num2
        entry = ("{} + {} = {}".format(num1,num2,calculation))
        print(entry)

    elif operator == "-":
        calculation = num1 - num2
        entry = ("{} - {} = {}".format(num1,num2,calculation))
        print(entry)

    elif operator == "*":
        calculation = num1 * num2
        entry = ("{} * {} = {}".format(num1,num2, calculation))
        print(entry)

    elif operator == "/":
        calculation = num1 / num2
        entry = ("{} / {} = {}".format(num1, num2, calculation))
        print(entry)




if __name__ == '__main__':
    while True:
        number = choose_numbers()
        try:
            choose_operator(number["num1"], number["num2"])
        except ZeroDivisionError:
            print("You cannot divide by zero. Please try again!")
0
Rui Vieira On

I would say that you're missing an external while to maintain the loop until the program reaches the answer N for the choice.

Additionally, you could segregate the tasks in your code using functions, to turn it more understandable and maintainable. Something like that, at main flow:

while True
    get_numbers()
    get_operation()
    do_calculation()
    get_choice()

At get_numbers() accept the numbers with first while loop for validation.

At get_operation() accept the operation. I suggest implement a similar while to validate the operations allowed.

At do_calculation() maintain just the if/elif structure, with the try for preventing division by zero error (while doesn't aply here)

At get_choice() accept the decision to continue with more calculations or quit, but remember to validate both options Y or N, and maybe convert input to upper. In the same way, a while is welcome to guarantees that user enter a valid choice.