Try This: Execute Statements from a String

While Python's built-in eval() function is for evaluating expressions embedded in strings, its exec() function can actually execute Python statements.

Remember that a string that starts and ends with triple-quotes """ can span multiple lines!

Let's try adding statements contained in a string, and then executing them with the exec() function.

Example script: embed_try_this

  • Change project's name from  embed_intro to embed_try_this.
  • Make the changes shown below.
  • Save the modified script.
  • Click the Send to micro:bit button.
# embed_try_this

from microbit import *

sleep(1000)

s = "1 + 2 + 3 + 4"
reps = eval(s)

print("reps = ", reps)

s = """                   # <- add
print('Start counting:')  # <- add
for n in range(0, reps):  # <- add
    print('n = ', n)      # <- add
"""                       # <- add

exec(s)                   # <- add

print('Done!')            # <- add
  • Check the results in the serial monitor.
  • Verify that the terminal displays a count-to-ten sequence.  If so, it means that exec(s) took those Python statements embedded in the string s and executed them.