Embed Code in Strings

Strings can contain Python expressions, or even one or more Python statements.  So long as those strings are passed to the correct functions, an incoming string can be evaluated as an expression or even executed as one or more Python statements! 

Security heads up! If you are going to set up an app that can run scripts you can type in, you will also have to make sure that only you and others with permission can send text with embedded scripts to your app!Let's start with evaluating an expression that's in a string.

Example script: embed_intro

  • Enter this script and save it as embed_intro.  
  • Flash the script into the micro:bit.
# embed_intro

from microbit import *

sleep(1000)

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

print("reps = ", reps)
  • Open the terminal.
  • Verify that the result is reps = 10.

How embed_intro Works

The script starts with the string s = "1 + 2 + 3 + 4".  Then, eval(s) evaluates 1 + 2 + 3 + 4 as a Python expression and returns 10.  Since reps = eval("1 + 2 + 3 + 4"), the result of 10 is stored as an int in reps.