-1

I want to make a gui calculator which takes input as a string through buttons

The buttons their content over to a function where they just concatenate and

I have used eval() function for solving the expression I get through entry.get()

Can anyone tell how can we solve square root within the expression we get like =2+346-677*78/6+√567+7... Something like that ,using eval() only or any other editing in the code or expression that will help eval() to solve the square root problem also that is taken as input in form through button

Buddy Bob
  • 5,829
  • 1
  • 13
  • 44

2 Answers2

0

you use math.sqrt()

from math import sqrt
print(eval("2+346-677*78/6+sqrt(567)+7"))

output

-8422.188238200419

or if you want only the number containing you can try the following

from math import sqrt
import re
stringEx = "2+346-677*78/6+√567+7"
solved = [sqrt(float(sqrts)) for sqrts in [x.replace('√','') for x in re.split('[+\-]',stringEx) if '√' in x]]

output

[23.811761799581316]
Buddy Bob
  • 5,829
  • 1
  • 13
  • 44
0

You can also use Regex:

import re
import math

def replace(expression):
    # Replace the sqrt symbol with the sqrt funcion from the math module
    return eval(re.sub(r'√(\d+)', r'math.sqrt(\1)', expression))
   
print(replace("√100"))                  # 10.0
print(replace("√25 + √36"))             # 11.0
print(replace("2+346-677*78/6+√567+7")) # -8422.188238200419

Note that this will not work for complex expressions:

print(replace("√(3**2 + 4**2)")) 
# raises SyntaxError: invalid character in identifier
enzo
  • 9,861
  • 3
  • 15
  • 38