-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?

3
  • 1
    Does this answer your question? What's the difference between eval, exec, and compile? Commented Mar 10, 2020 at 12:56
  • eval and exec are the correct solution, and they can be used in a safer manner. Commented Mar 10, 2020 at 12:57
  • How and why did you create this string? Commented Mar 10, 2020 at 13:01

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.