Answer to Question #197725 in Python for vinay

Question #197725

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


1
Expert's answer
2021-05-24T00:12:25-0400
def num_check(num):
    try:
        int(num)
        return True
    except ValueError:
        return False


nums = input('Enter a math expression (integers and operator similar to "3 + 5"): ').split()
if len(nums) == 3:
    if num_check(nums[0]) and num_check(nums[2]):
        if nums[1] in '+-*/%':
            if nums[1] == '+':
                print(' '.join(nums), '=', int(nums[0]) + int(nums[2]))
            elif nums[1] == '-':
                print(' '.join(nums), '=', int(nums[0]) - int(nums[2]))
            elif nums[1] == '*':
                print(' '.join(nums), '=', int(nums[0]) * int(nums[2]))
            elif nums[1] == '/':
                print(' '.join(nums), '=', int(nums[0]) / int(nums[2]))
            elif nums[1] == '%':
                print(' '.join(nums), '=', int(nums[0]) % int(nums[2]))
        else:
            print('Unexpected operator. Expected one of +, -, *, / or %')
    else:
        print('One of the numbers is incorrect')
else:
    print('Invalid expression')

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