Bharat Bharat - 1 year ago 76
Python Question

This python code is not solving equations

I have a chat bot for an Instant messenger and I am trying to make a math solver for it but it can't send the solution of equation to the Instant messenger, it sends equation instead.

If someone from Instant messenger sends "solve: 2+2", this program should send them "4" not "2+2".

Main problem:

if (parser.getPayload().lower()[:6]=="solve:"):
parser.sendGroupMessage(parser.getTargetID(), str(parser.getPayload()[7:]))


it's sending same input again not the answer of equation

I tested something and that's working properly. If I add this code, program will send solution of equation:

if (parser.getPayload().lower()=="test"):
parser.sendGroupMessage(parser.getTargetID(), str(2 + 2 -3 + 8 * 7))

Working perfectly

Answer Source

What you need to do this evaluating math expressions in string form.

However, user inputs are dangerous if you are just eval things whatever they give you. Security of Python's eval() on untrusted strings?

You can use ast.literal_eval to lower the risk.

Or you can use a evaluator from answers of following question Evaluating a mathematical expression in a string

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download