0

I made a calculator, but I can't figure out how to use try-except function properly, I've tried many solutions I found on the internet but none helps.

My calculator:

import math

print("Calculator")
number1 = input("Give a number:")
number2 = input("Give a number:")

while True:
    print("(1) +")
    print("(2) -")
    print("(3) *")
    print("(4) /")
    print("(5)sin(number1/number2)")
    print("(6)cos(number1/number2)")
    print("(7)Change numbers")
    print("(8)Quit")
    print("Current numbers: ", number1, number2)
    selection = (int(input("Please select something (1-6):")))
    if selection == 1:
        print("The result is:", number1 + number2)

    if selection == 2:
        print("The result is:", number1 - number2)

    if selection == 3:
        print("The result is:", number1 * number2)

    if selection == 4:
        print("The result is:", number1 / number2)

    if selection == 5:
        print("The result is:", math.sin(number1 / number2))

    if selection == 6:
        print("The result is:", math.cos(number1 / number2))

    if selection == 7:
        number1 = int(input("Give the first number:"))
        number2 = int(input("Give the second number:"))

    if selection == 8:
        print("Thank you!")
        break

I tried this both outside the while loop and inside:

number1 = input("Give a number:")
try:
    number1 = int(number1)
except ValueError:
    print("Invalid number.")
number2 = input("Give a number:")
try:
    number2 = int(number2)
except ValueError:
    print("Invalid number.")

If i don't put an int value it gives error "invalid number." but still continues with the code, when 2 inputs are given, nr or string doesnt mather it still continues like this ( end part ):

(7)Change numbers
(8)Quit
Current numbers:  24 d
Please select something (1-8)
Gritty21
  • 3
  • 4
  • Put input into a separate function, where you use a *loop* until a correct input is given, and then return that input (suitably converted). – Some programmer dude Feb 08 '22 at 11:03
  • You can put the whole code you have in the loop in the `try`. Also you should add the `except ZeroDivisionError` clause. – tromgy Feb 08 '22 at 11:14

0 Answers0