2
string = "if X > 3 :\n   print(\"X is Greater\")\nelse :\n   print(\"X is Lesser\")"

""" It prints the string as an indented code of if else statements if X is greater than 3
X is greater else it prints X is lesser"""

X = 6

eval(string)

Can eval() in python be used in this way or is there anything I'm missing .

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Pinkoo
  • 127
  • 7

1 Answers1

3

eval is used only for expressions. From the documentation

The expression argument is parsed and evaluated as a Python expression

Use exec here

>>> string = "if X > 3 :\n   print(\"X is Greater\")\nelse :\n   print(\"X is Lesser\")"
>>> X = 6
>>> exec(string)
X is Greater

However do note that both the statements are quite risky to use. (See eval really is dangerous)

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140