Skip to content

Course home

Develop code

Develop code

EasyMediumHard
123456789101112
Question 1

Amina is writing a Python program to encrypt messages using a Caesar cipher.

The Caesar cipher works by shifting each letter of a message forward in the alphabet by a set number of places (the key).

For example, with a key of +3, the word code becomes frgh:

Plaintextcode
Ciphertextfrgh

Amina has already written the helper function encrypt(text, key) which performs the character shifting.

She needs you to complete the rest of the program to meet these requirements:

  1. Input a plaintext message from the user.
  2. Input an integer key from the user.
  3. Validate the key: it must be between 1 and 15 inclusive. The program must repeatedly prompt the user until a valid key is entered.
  4. Call the encrypt function with the plaintext and valid key to generate the ciphertext.
  5. Write the ciphertext to a text file named secret.txt.
  6. Display the ciphertext on the screen.

Complete the Python 3 program code below:

def encrypt(text, key):
    ciphertext = ""
    for char in text:
        if char.isalpha():
            start = ord('a') if char.islower() else ord('A')
            ciphertext += chr((ord(char) - start + key) % 26 + start)
        else:
            ciphertext += char
    return ciphertext

# --- COMPLETE THE PROGRAM BELOW THIS LINE ---
[8]
Markscheme

Develop code Questions

  1. IGCSE
  2. /Computer Science
  3. /Develop code

62 exam-style questions on Edexcel IGCSE Computer Science Develop code. Each one has a worked solution and a mark scheme showing where the marks go.

Question bank