Try This: Print Alphabets

The variable name s is often used in scripts to name strings.  In scripts where many string operations are performed, s might be used repeatedly as a temporary or working variable  that ends up being many different strings, each for a brief period of time.  Strings in the script that have important meanings should be given descriptive names.  One example would be password  = "abc123".  

The variable name c can often be found as the name of a string if it stores a single character.  

A built-in function is one that's always there in Python, no module importing required.  For strings, Python has four important built-in functions:

  • ord() — Returns the ASCII value of a character
  • char() — Returns the character of an ASCII value
  • len() — Returns the length of a string
  • str() — Converts other types of objects to string

The ord() and char() functions were just used in the last example script, and you will get to experiment with len() and str() in another activity.

The first 32 ASCII codes are control characters intended for older printers and storage devices.  Some of them are still used with terminals today.  For example ASCII character 10, the line feed character, causes the Python terminal's cursor to move down a line.  In the previous activity, you used the escape sequence \n to add the ASCII 10 to strings.

Printable characters range from 32 (space) to 126 (~).  As you have seen from experimentation, the upper-case alphabet is codes 65 through 90, the lower-case alphabet is 97-122, and digits are 48-57.

Imagine a script that repeatedly calls the chr() function inside a for... loop.  The first time, it prints chr(65), the second time, it prints chr(66), and continues all the way through chr(90).  What do you think you'd see?  

Example script: chars_in_strings_try_this

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

from microbit import *

sleep(1000)

for n in range(65, 91):
    c = chr(n)
    print(c)
    sleep(250)
  • Open the terminal.
  • Verify that the terminal displays the characters A through Z.

  • For lowercase characters, try changing for n in range(65, 91) to for n in range(97, 123) and re-flashing the script.  See the difference?
  • How about characters that represent digits?  Try for n in range(48, 58).