The program calculator, in which you need to put exceptions on the input of operations, numbers and division by 0. I wrote a code with two exceptions, I can not understand what the error is. Help to correct.

while True: s = input("Знак (+,-,*,/): ") try: if s in ('+','-','*','/'): except ValueError: print("Неверный знак операции!") else: x = float(input("x=")) y = float(input("y=")) if s == '+': print("%.2f" % (x+y)) elif s == '-': print("%.2f" % (xy)) elif s == '*': print("%.2f" % (x*y)) elif s == '/': try: if y == 0: except AssertionError: print("Деление на 0") else: print("%.2f" % (x/y)) 

    2 answers 2

     def addition(x, y): return x + y def subtraction(x, y): return x - y def multiplication(x, y): return x * y def division(x, y): return x / y operations = { '+': addition, '-': subtraction, '*': multiplication, '/': division } while True: sign = input('Знак (+, -, *, /): ') if sign == 'exit': break try: operation = operations[sign] x = float(input('x = ')) y = float(input('y = ')) print('{0:.2f}'.format(operation(x, y))) except KeyError: print('Неверный знак операции!') except ZeroDivisionError: print('Деление на 0!') except ValueError: print('Не удалось преобразовать в число!') 

      In the try block, you need to put not a check, but a piece of code in which we expect a potential problem. Verification is not needed at all - the mechanism for catching exceptions replaces them.

      In addition, you have a confusion with when to throw an exception, and when to catch it. Read more, for which exceptions are generally needed.

      Well, never in any case after the line starting with if can not be a line with a smaller indent.

      You need something like this:

       import operator OPER_MAP = { '+': operator.add, '-': operator.sub, '*': operator.mul, '/': operator.truediv, } def calculator(): s = input("Знак (+,-,*,/): ") if s not in OPER_MAP: raise ValueError() x = float(input("x=")) y = float(input("y=")) if s == '/' and y < 0: # Просто для примера. # На самом деле, такое исключение и так бы выбросилось # при попытке делить на ноль # и эту проверку можно вообще убрать raise ZeroDivisionError operation = OPER_MAP[s] print(operation(x, y)) while True: try: calculator() except ValueError: print("Такой арифметической операции не существует, попробуйте ещё раз") except ZeroDivisionError: print("Делить на ноль нельзя, попробуйте сначала") 

      (The code is designed for the third python. For the second, in particular, you need to truediv replace with div)