Your Turn: Check Every Character

Now that your script can access the length of a string, it can use that number to limit how many characters the script checks in a loop.  This makes it possible to access every character safely, without accidentally using an index value that's too large.

This script displays both the individual characters in the string along with their ASCII codes.

Example script: char_access_your_turn

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

from microbit import *

sleep(1000)

s = "ABCDEF 12345"

print("Characters in s:")

length = len(s)

print("length =", length)
print()

for n in range(length):
    c = s[n]
    a = ord(c)
    print("s[", n, "] =", c, "| ASCII:", a)

print()
  • Open the terminal.
  • Verify that it displays all the characters in the s string along with their ASCII codes.