Write a program to create a menu-driven calculator that performs basic arithmetic operations (+, -, *, /, and %).
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')
Comments
Leave a comment