Question #70180
you will write a program that prompts the user for two integers and one of the 4 basic mathematical operations. The only valid choices are: add, subtract, multiply, or divide (use true division and not integer division). The user can type the operation using any combination of upper case and lower case letters. If the user types in an operation that is not defined, the program should simply tell the user the operation is not a valid operation (See sample run 1). Assuming the user's operation is defined, you will perform the operation, print the operands, print the operation (the way the user typed it), and the result. If the second integer input is zero and the desired operation is division, don't print the result, instead print that "Division by zero is not allowed" (See sample run 2). After printing the result, display a line and print out any of the three messages below that is true:
Both operands were negative
Both operands were positive
The result has three or more digits in it
Answer
def main():
operations = {'add': lambda x, y: x + y, 'subtract': lambda x, y: x - y, 'multiply': lambda x, y: x * y, 'divide': lambda x, y: float(x) / float(y)}
# Read operands and operator
x = int(raw_input('x='))
y = int(raw_input('y='))
operator = raw_input('operator: ')
# Check if we got valid operator
if operator.lower() not in operations.keys():
print('Error. Invalid operation.')
return
# Print operands and operator
print('\n')
print('%d %d %s' % (x, y, operator))
# Check for zero division
if operator == 'divide' and y == 0:
print('Division by zero is not allowed')
return
# Calculate result value
z = operations[operator.lower()](x, y)
# Print result
print('Result: %.4f' % (z,))
# Print empty line
print('\n')
# Additional information
if x < 0 and y < 0:
print('Both operands were negative')
elif x > 0 and y > 0:
print('Both operands were positive')
# Count number of digits for integer part
n, temp = 0, int(z)
if temp < 0: temp = -temp
while temp > 0:
temp /= 10
n += 1
# Count how much digits after decimal point
if str(z)[::-1].find('.') != -1:
n += str(z)[::-1].find('.')
if n >= 3:
print('The result has three or more digits in it ')
if __name__ == '__main__':
main()Answer provided by www.AssignmentExpert.com