Answer to Question #165146 in Python for raj

Question #165146

Write a program to create a menu-driven calculator that performs basic arithmetic operations (+, -, *, /, and %).Input


The input will be a single line containing two integers and operator(+, -, *, /, and %) similar to 3 + 5.Output


If the given operator is "+", print the sum of two numbers.

If the given operator is "-", print the result of the subtraction of the two numbers.

If the given operator is "*", print the multiplication of the two numbers.

If the given operator is "/", print the result of the division of the two numbers.

If the given operator is "%", print the result of the modulus operation of the two numbers.Explanation


For example, if the given operator is "+" and the two numbers are 3 and 5. As it is an addition operator, your code should print the sum of the given two numbers (3 + 5), which is 8.

Similarly, if the given operator is "*" and the two numbers are 2 and 5.

As it is a multiplication operator, your code should print the result of the multiplication of the given two numbers (2 * 5), which is 10.

Similarly, if the given operator is "-" and the two numbers are 10 and 9.

As it is a subtraction operator, your code should print the result of the subtraction of the given two numbers (10 - 9), which is 1.


1
Expert's answer
2021-02-24T03:24:31-0500
import re

print(">>> Calculator with basic operations (+, -, *, /, and %) <<<\n")
while True:
   operation = input("Pattern for calculation: <integer> <operator> <integer>, 'Q' or 'q' to quit: ")
   try:
      # mo - match object
      mo = re.match(r"\A\s*(\d+)\s*([*+-/%]{1})\s*(\d+)\s*\Z|\A\s*([Qq]{1})\s*\Z", operation)
      if not mo:
         raise ValueError
      if mo.group(4) in ('Q', 'q'):
         #print(mo, mo.groups())
         break
      #print(mo, mo.groups())
      int1 = int(mo.group(1))
      op = mo.group(2)
      int2 = int(mo.group(3))
      if op == '+':
         res = int1 + int2
      elif op == '-':
         res = int1 - int2
      elif op == '*':
         res = int1 * int2
      elif op == '/':
         res = int1 / int2
      elif op == '%':
         res = int1 % int2
      print(end = ' = ')
      print(res, '\n')
   except ValueError:
      print("Error: Wrong pattern or operation! Try it again.\n")
   except ZeroDivisionError:
      print("Error: Integer division or modulo by zero! Try it again.\n")

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS