-1

I have a little problem, I have written a for loop as a string.

In PHP, with the help of function exec(), we can run the string which will eventually run the for loop defined inside the string.

Can we do such a thing in Python as well?

By example, I would like run follow it:

string="for i in range(1,(5+1)): print(str(i))"

How to run this in Python?

oguz ismail
  • 1
  • 16
  • 47
  • 69
cleanet
  • 71
  • 6
  • 1
    Does this answer your question? [What's the difference between eval, exec, and compile?](https://stackoverflow.com/questions/2220699/whats-the-difference-between-eval-exec-and-compile) – lucidbrot Mar 10 '20 at 12:56
  • eval and exec are the correct solution, and they can be used in a safer manner. – Freeman Mar 10 '20 at 12:57
  • How and why did you create this string? – Tomerikoo Mar 10 '20 at 13:01

1 Answers1

1

You can use exec if you want to execute some statements:

code = 'for i in range(1,(5+1)): print(str(i))'
exec(code)

If you want to evaluate an expression and get the value then you can use eval:

value = eval('2+3')
print(value) # 5
maestromusica
  • 706
  • 8
  • 23