string = input()
string = (''.join([str(eval(s)) if ('(' in s and ')' in s) else s for s in string.split(' ')]))
print(string)
with this code there are some problems:
if I write 5-(2-sp.sqrt(4)) it will give me an EOF error because it will split the words in a way that sp.sqrt(4) will be sp.sqrt(4)). It should be sp.sqrt(4)
if i write '2-10' it won't evaluate it and will just return '2-10'; it should return '-8'. While if I write '2-10*(2-5)' it will return the write answer.
instead of just don't evaluate the part that the code doesn't recognize, it will give me an error saying that the part not recognized isn't defined. (ex. '2+x-10-(5*10)' ---- name 'x' is not defined. It should return: 'x-58'
Issue - 1:
it will give me an EOF error because it will split the words in a way that sp.sqrt(4) will be sp.sqrt(4))
['5-(2-sp.sqrt(4))']
sp
)Issue - 2:
if I write '2-10' it won't evaluate it and will just return '2-10' but when I write '2-10*(2-5)' it will return the write answer.
It is because you have called the eval() function only if there are both '(' and ')'
Issue - 3:
It is because eval() takes only valid python expressions ( you can't put an un-declared variable directly inside the parameter). In your case x was not declared before.
Solution:
There is a sympy function parse_expr
which probably does what you want here:
In [20]: from sympy import parse_expr
In [21]: parse_expr('5-(2-sqrt(4))')
Out[21]: 5
In [22]: parse_expr('2-10')
Out[22]: -8
In [23]: parse_expr('2+x-10-(5*10)')
Out[23]: x - 58