The worksheetDownload the PDF
Answers

F3.2 Character codes and conversion

Strings, lists and records · GCSE · OCR J277 2.2.2, AQA 8525 3.2.8, Edexcel 1CP2 6.3.3 · about 15 min

BugBotLab

What this lesson is about

ord and chr, ASCII, comparing strings, and a Caesar cipher.

Questions 7 marks in all

  1. [1 mark]What does this program print?

    print(ord("A"), ord("a"))
    Answer:
    65 97

    In ASCII, A is 65 and lower case starts 32 later, at 97.

  2. [1 mark]What does this program print?

    print(chr(66) + chr(111) + chr(116))
    Answer:
    Bot

    chr turns each code back into its character: B, o, t.

  3. [1 mark]ord("A") is 65. What is ord("E")?

    Answer: 69. The capital letters are in order, so E is 4 after A.
  4. [1 mark]Why is "Zebra" < "apple" True?

    1. ACapital Z has a smaller character code than lower-case a
    2. BZebra is a shorter word
    3. CPython sorts words backwards
    4. DIt is False
    Answer: A. Strings compare by character code, and every capital letter comes before every lower-case letter.
  5. [1 mark]What does this program print?

    letter = "Y"
    code = (ord(letter) - ord("A") + 3) % 26
    print(chr(code + ord("A")))
    Answer:
    B

    Y is letter 24; 24 + 3 is 27, and 27 % 26 is 1, which wraps round to B.

  6. [1 mark]Which AQA pseudo-code function gives the code for a character?

    1. ACHAR_TO_CODE
    2. BASC
    3. Cord
    4. DSTRING_TO_INT
    Answer: A. AQA uses CHAR_TO_CODE and CODE_TO_CHAR. OCR's Reference Language uses ASC and CHR; Python uses ord and chr.
  7. [1 mark]What does this program print?

    print("42".isdigit(), "4two".isdigit())
    Answer:
    True False

    isdigit is True only when every character is a digit.

The task: shift the letters

Ask Message? and print the message with every letter moved one place along the alphabet. The task answers HAL (the computer in a famous film), and the answer is the name of a famous computer company. The message will be capital letters only. Work it out with ord and chr.

# the two lines every program starts with: the commands, then the robot
from bugbot import *
connect()

message = input("Message? ")
secret = ""

The hint students can ask for: Turn each letter into its code number, move it along by one, and wrap back to the start of the alphabet when it runs past Z. Build the answer up one letter at a time.

A solution

from bugbot import *
connect()
message = input("Message? ")
secret = ""
for letter in message:
    code = (ord(letter) - ord("A") + 1) % 26
    secret = secret + chr(code + ord("A"))
print(secret)

Any program that meets the task's checks is marked correct in the simulator; this is one way, not the only way.