I want to write a Python string that when executed does this:
if condition:
consequence
else:
alternative
So, I tried something like:
string = 'if condition: consequence; else: alternative;'
to be executed with:
>>> exec(string)
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
exec(string)
File "<string>", line 1
if condition: consequence; else: alternative;
^
SyntaxError: invalid syntax
But as you see, I get a syntax error. How should the string be formatted?
Thanks for the help!
PS: this question is not about how to evaluate or execute Python strings (See instead How do I execute a string containing Python code in Python?), but about the formatting required to execute an if..then..else clause.
Some context:
I am following the book "understanding computation" by Tom Stuart. Part of it is about understanding how programming languages work. So he gives example code for the implementation of a toy language 'SIMPLE'. He shows code in Ruby how to translate SIMPLE into Ruby code. However, I am trying to write this in Python, as that interests me more. The Ruby example is:
def to_ruby
"-> e { if (#{condition.to_ruby}).call(e)" +
" then (#{consequence.to_ruby}).call(e)" +
" else (#{alternative.to_ruby}).call(e)" +
" end }"
end