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

  • Enter this script and save it as embed_try_this.  
  • Flash the script into the micro:bit.
# 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
  • Open the terminal.
  • 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.