I need some help with part of a program. python 3.6 def calc(expr): #expr: nonem
ID: 3852802 • Letter: I
Question
I need some help with part of a program. python 3.6
def calc(expr):
#expr: nonempty string that is an arithmetic expression
#the fuction returns the calculated result
if not isinstance(expr,str) or len(expr)<=0:
print("argument error: line A in eval_expr") #Line A
return "argument error: line A in eval_expr"
#Hold two modes: "addition" and "multiplication"
#Initializtion: get the first number
newNumber, newOpr, oprPos = getNextNumber(expr, 0)
if newNumber is None:
print("input formula error: line B in eval_expr") #Line B
return "input formula error: line B in eval_expr"
elif newOpr is None:
return newNumber
elif newOpr=="+" or newOpr=="-":
mode="add"
addResult=newNumber #value so far in the addition mode
mulResult=None #value so far in the mulplication mode
elif newOpr=="*" or newOpr=="/":
mode="mul"
addResult=0
mulResult=newNumber
pos=oprPos+1 #the new current position
opr=newOpr #the new current operator
#start the calculation. Use the above functions effectively.
while True:
Explanation / Answer
Instead of going through all this mess of operations for calculating mathematical expression inside string you can change your calc(expr) functions definition to more simplified form by using eval() function which returns mathematical answer from a string containing mathematical expression
script.py
def calc(expr):
#expr: nonempty string that is an arithmetic expression
#the fuction returns the calculated result
if not isinstance(expr,str) or len(expr)<=0:
print("argument error: line A in eval_expr") #Line A
return "argument error: line A in eval_expr"
return(eval(expr)) # the eval function here returns the calculated result