-2

I tried with exec() but it doesn't work for what i'm trying to do:

math = "1 + 1"
a = exec(math)
print(a)

when "a" is printed i get

None

how can i do something like this?

Patientes
  • 113
  • 1
  • 1
  • 7
  • You can try `eval()` but it will only be executed once. What exactly are you trying to do? – sj95126 Aug 14 '22 at 19:23
  • 1
    `exec()` doesn't return the value. You would have to include the assignment in the exec expression: `exec("a = 1 + 1")`. However, this is almost certainly a terrible idea, and there must be a better way to do what you want. – John Gordon Aug 14 '22 at 19:25
  • i need to take a math operation as input to use it for some stuff. I thoght this was the fastest way to do this but as i see it's very unsafe. – Patientes Aug 14 '22 at 19:28
  • You’re probably better off using something like sympy. – bob Aug 14 '22 at 19:41

1 Answers1

2
exec("a = 1 + 1")
print(a)
2
b = eval("1 + 1")
print(b)
2

You're getting None because exec always returns None, instead it execute the expression. What you might want is eval, it returns whatever is evaluated inside.

Notice that both of them are quite dangerous as malicious programs can easily assess your data by input.

Why is using 'eval' a bad practice?

Clydinite
  • 183
  • 4