Answer to Question #166021 in Python for mani

Question #166021

Simple Calculator - 2

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.


1
Expert's answer
2021-02-23T07:20:50-0500
def IsInt(str):
    try: 
        int(str)
        return True
    except ValueError:
        return False

txt = input('Please enter a math expression: ')
fields = txt.split()

if len(fields) != 3:
    print("Error: invalid expression. Expected single line containing two "
          +"integers and operator similar to '3 + 5'")
    exit(1)

if not IsInt(fields[0]) or not IsInt(fields[2]):
    print("Error: one of the numbers is incorrect ")
    exit(1)

if fields[1] not in set(['+','-','*','/','%']):
    print("Error: unexpected operator. Expected one of +, -, *, /, and %")
    exit(1)

operand1 = int(fields[0])
operand2 = int(fields[2])

if fields[1] == '+':
    result = operand1 + operand2
elif fields[1] == '-':
    result = operand1 - operand2
elif fields[1] == '*':
    result = operand1 * operand2
elif fields[1] == '/':
    result = operand1 / operand2
elif fields[1] == '%':
    result = operand1 % operand2

print(txt, "=", result)

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