-3

How to get a Computational string like ((2*3)+(3-1))+(4/2)) and return the answer in python?

I can't use eval func. the inputed pharase should include parantheses. The program must take into account priorities when calculating.

  • 3
    Does this answer your question? [Safe expression parser in Python](https://stackoverflow.com/questions/3582403/safe-expression-parser-in-python) – Fred Larson Nov 17 '20 at 18:08

3 Answers3

0

Use eval. like this: ans = eval('((2*3)+(3-1))+(4/2))')

yakir0
  • 184
  • 6
  • you should've mention that in the question. – yakir0 Nov 17 '20 at 18:26
  • you can 'cheat' by using `exec` like `exec('x =((2*3)+(3-1))+(4/2)) ')` and then accessing the variable `x`. if this is also not good, you need to create your own function for that. – yakir0 Nov 17 '20 at 18:30
0

for that you gotta use the eval() function. It makes a string into a python code. One way to apply it would be

def convert_to_code(some_string):
   
   return eval(some_string)


user_input = input()

result = convert_to_code(user_input)

print(result)

I find it easier to have a dedicated funtion to return eval() in cases with mathematical equations that you'll have to change the value of a variable x multiple times. For example, if you know numerical methods, when trying to create a programm that calculates a polynomial's root, how i did it would be very usefull. But you could just use eval() it self.

yna ponte
  • 41
  • 5
0

Get the string with e = input("Your question :").
You can calcul the string with e = eval(e) and you can show it with print(e).

The complete code :

e = input("Your question :")
e = eval(e)
print(e)
Virinas-code
  • 180
  • 3
  • 14
  • @shaqayegh78 I'm sorry but I can't help you. You can see the reply of @user14654909 on `exec` function. An example : `e = input("Your question:");f = exec("e="+e);print(e)` – Virinas-code Nov 19 '20 at 12:41