0

How to make a function that can interpret a string as a code ?

var1 = 5
var2 = 10
var3 = 7

str = "(var1*var2)+var3"


result = calculate(str) # I need help to write this function

result should output 57

FObersteiner
  • 22,500
  • 8
  • 42
  • 72
shikata
  • 95
  • 1
  • 11
  • 1
    Does this answer your question? [Evaluating a mathematical expression in a string](https://stackoverflow.com/questions/2371436/evaluating-a-mathematical-expression-in-a-string) – Chris Feb 25 '22 at 15:29
  • You could use the `eval()` function which evaluates a string as code but be aware that there are security problems with this if the code is coming from an external source / being inputted – Lecdi Feb 25 '22 at 15:34

1 Answers1

0

Use result = eval(str) instead of result = calculate(str).

Disclaimer: eval() should be used carefully since it can execute anything passed to it. More details can be found in this article.

FObersteiner
  • 22,500
  • 8
  • 42
  • 72
  • 3
    *Please* add a disclaimer as to why `eval` should be used with *great* care and control. `ast.literal_eval` might be a better (safer) solution. – S3DEV Feb 25 '22 at 15:35
  • `ast.literal_eval()` would not work in this case as the string is not a literal, but they should definitely add an explanation as to why `eval()` should be used carefully – Lecdi Feb 25 '22 at 15:39