136k views
5 votes
Write a program that will read and evaluate a mathematical expression. The expression is of the form: oprand1 op operand2, where operand1 and operand2 are positive integers and op is an operator, which is either +, -, * or /. For example: 24 + 65 and 276 * 2 are legal expressions. Assumption: There is a single space between each operand and the operator.

1 Answer

4 votes

Answer:

ques=(input("Enter question "))

br = ques.split()

operand1= int(br[0])

operand2= int(br[2])

op= br[1]

if (operand1 >0 and operand2 >0):

if op == '+':

print(operand1, "+", operand2, "=",operand1 + operand2)

elif op == '-':

print(operand1, "-", operand2, "=",operand1 - operand2)

elif op == '*':

print(operand1, "*", operand2, "=",operand1 * operand2)

elif op == '/':

print(operand1, "/", operand2, "",operand1 / operand2)

else:

print("Please enter a correct operator")

else:

print("Please ener a positive number")

Step-by-step explanation:

ques=(input("Enter question "))

This line prompts for an input like 2 + 23

br = ques.split()

The split function takes the input and breaks it into different parts and places it in a list with each element having an index number starting from zero

operand1= int(br[0])

operand2= int(br[2])

op= br[1]

we use the index numbers to access their location and assign them to operand1 operand2 and op(which is the operator). here we assign operand1 and operand2 to an integer data type and leave op as a string.

if (operand1 >0 and operand2 >0):

The if statement here ensures that both operand1 and two are positive.

if op == '+':

print(operand1, "+", operand2, "=",operand1 + operand2)

elif op == '-':

print(operand1, "-", operand2, "=",operand1 - operand2)

elif op == '*':

print(operand1, "*", operand2, "=",operand1 * operand2)

elif op == '/':

print(operand1, "/", operand2, "",operand1 / operand2)

checks the operators, carries out the calculation and prints the solution.

else:

print("Please enter a correct operator")

the else statements handles all possible errors that may occur when writing the operator

else:

print("Please enter a positive number")

This prompts the user to enter a positive number

Another approach would be to create functions for each operator and call those functions whenever the operator is inputted.

User Lim Min Chien
by
4.9k points