Python by Projects › Secret Codes

Exercises: Secret Codes

Take strings apart, clean them up, and build codes that a friend can decode. Predict before you run, then test with lowercase sample messages. Write all code in the blank work cells.

Exercise 1: Reverse a Word

Store " Stressed " in a variable. Use .strip() and .lower() to clean it, then use the slice [::-1] to reverse the cleaned word. Store each result and print the reversed word. Predict it first.

Real program

After the fixed version works, replace the fixed word with input(). Keep the same cleaning, reversing, and output.

How this is checked: You check this one yourself, against the list below.

The site cannot check this one. Run your program, then tick each item below when your work does it.

Check your work

For parents and teachers: report a problem

Exercise 2: First and Last

Store cipher in a variable named word. Select its first character with position 0 and its last character with position -1. Also slice out iph. Store all three pieces and print them in one f-string. Predict the output first.

Real program

After the fixed version works, replace the fixed word with input(). Keep the same character selections, slice, and output.

How this is checked: You check this one yourself, against the list below.

The site cannot check this one. Run your program, then tick each item below when your work does it.

Check your work

For parents and teachers: report a problem

Exercise 3: Grab the Middle

Store " sunflower " in a variable. Remove the outside spaces, use one slice to select flow, and select the first character of that slice. Store each result and print the middle piece and its first character. Remember that the stop position is not included.

Real program

After the fixed version works, replace the fixed word with input(). Keep the same cleaning, middle slice, character selection, and output.

How this is checked: You check this one yourself, against the list below.

The site cannot check this one. Run your program, then tick each item below when your work does it.

Check your work

For parents and teachers: report a problem

Exercise 4: Shout It and Print

Store " secret_launch " in a variable. Remove the outside spaces, replace the underscore with a space, change the result to uppercase, and store each changed string. Store the boolean from checking whether a space is in the final message. Print the final message and the boolean in an f-string.

Real program

After the fixed version works, replace the fixed message with input(). Keep the same cleanup, replacement, uppercase conversion, check, and output.

How this is checked: You check this one yourself, against the list below.

The site cannot check this one. Run your program, then tick each item below when your work does it.

Check your work

For parents and teachers: report a problem

Exercise 5: Is It a Vowel?

Read a short piece of text with input(), change it to lowercase, and store its first character in letter. Store aeiou in vowels. Write is_vowel = letter in vowels and print is_vowel so the boolean itself is visible. Store a second boolean for letter == "y" and print both checks in an f-string. Then use if / elif / else to print exactly one category: vowel, sometimes-vowel y, or consonant. Test once with a vowel and once with y or a consonant.

How this is checked: You check this one yourself, against the list below.

The site cannot check this one. Run your program, then tick each item below when your work does it.

Check your work

For parents and teachers: report a problem

Exercise 6: Encode My Typed Message

Write the lesson's encode(message, shift) function. Start with letters = "abcdefghijklmnopqrstuvwxyz", change the message to lowercase, and build an empty result string. For each message character, use membership to decide whether it should shift. Locate a letter by scanning with for position in range(26): and if letters[position] == letter:. Calculate new_position = (position + shift) % 26; add the new letter to the accumulator. Use elif letter == " " to copy spaces and else to copy other punctuation. Return the result.

Then read a message with input(), store the integer literal 3 in shift, call encode, and print the coded message in an f-string. Test with lowercase text that includes a space or punctuation mark.

How this is checked: You check this one yourself, against the list below.

The site cannot check this one. Run your program, then tick each item below when your work does it.

Check your work

For parents and teachers: report a problem

Exercise 7: Fix the Caesar Wrap

Run the first buggy cell below yourself. It stops with an error on purpose. Before changing any code, read the real traceback. In the blank repair cell, write a comment that copies its LAST line exactly and a second comment naming the failing operation. Only then rewrite encode with % 26, print encode("zoo", 3), and explain in a comment why the first output character is c.

For a second short traceback-reading round, run the next buggy cell. Again copy the real LAST traceback line and name the failing operation in comments before fixing the position to the last valid alphabet position and printing that letter.

How this is checked: You check this one yourself, against the list below.

The site cannot check this one. Run your program, then tick each item below when your work does it.

Check your work

For parents and teachers: report a problem

Exercise 8: Secret Word Report

Read a message with input(). Store a cleaned lowercase copy, its first character, its last character, and a slice containing its first three characters. Store the boolean from checking whether "code" is in the cleaned message. Print all five results in f-strings, including the stored boolean. Test with a mixed-case message that has outside spaces.

How this is checked: You check this one yourself, against the list below.

The site cannot check this one. Run your program, then tick each item below when your work does it.

Check your work

For parents and teachers: report a problem

Exercise 9: Classify a Code Character

Read a short piece of text with input(), remove outside spaces, change it to lowercase, and store its first character. Also store the first two cleaned characters as a slice. Store and print the boolean from checking whether the character is in "abcdefghijklmnopqrstuvwxyz". Then write an if / elif / else chain that prints exactly one category: vowel, consonant letter, or mark. Use membership for both letter categories, and print the saved two-character slice in the category message. Test a vowel, a consonant, and a mark in separate runs.

How this is checked: You check this one yourself, against the list below.

The site cannot check this one. Run your program, then tick each item below when your work does it.

Check your work

For parents and teachers: report a problem

Exercise 10: Compare Two Integer Shifts

Write a fresh encode(message, shift) function so this exercise works on its own. Lowercase the message, rebuild an output accumulator with +, and use membership plus the nested alphabet-position scan from Exercise 6. Use if / elif / else to shift letters, copy spaces, and copy other marks. Return the result.

Call encode("Secret zoo!", 3) and encode("Secret zoo!", 5). Store both outputs, print both in f-strings, compare them with ==, and print that boolean. Then print the first character and the first three-character slice of each output. Explain which integer shift moves the first letter farther through the alphabet.

Real program

After the fixed version works, read the message with input() and each shift with int(input()). Keep the same two encodings, comparison, slices, and output.

How this is checked: You check this one yourself, against the list below.

The site cannot check this one. Run your program, then tick each item below when your work does it.

Check your work

For parents and teachers: report a problem

Exercise 11: Build an Atbash Decoder

Define decode_atbash(message). Lowercase the message and build an empty decoded-text accumulator. For each character, use membership to decide whether it is a letter. For a letter, use a nested for position in range(26) scan and compare letters[position] with the character. Add letters[25 - position] to the accumulator. Use elif to copy a space and else to copy another mark. Return the decoded text.

Call the function with "hvxivg!". Store and print the result in an f-string, then print its first character and its first three-character slice.

Real program

After the fixed version works, replace the fixed coded message with input(). Keep the same decoding, character selection, slice, and output.

How this is checked: You check this one yourself, against the list below.

The site cannot check this one. Run your program, then tick each item below when your work does it.

Check your work

For parents and teachers: report a problem

Algorithm Extension

Extra loop practice — optional enrichment: these drills reuse the same loop shapes on small fixed data, so try as many as you like.

Exercise 12: Count the vowels

Start with message = "Secret Code" and vowel_count = 0. Loop over message.lower(). Check each character once with membership in "aeiou"; when it matches, bump vowel_count by 1. Print the final count in a friendly f-string.

Pattern Spotlight retrieval: Which pattern is this, and which variable holds the count-so-far? Variation axis — data: characters in a string replace the home exercise's boolean answer results.

Real program

After the fixed version works, replace the fixed message with input(). Keep the same vowel-counting loop and output.

How this is checked: Checked by tests that run your code.

Also check yourself

The automatic check cannot see these, so tick each one when your work does it.

For parents and teachers: report a problem

Exercise 13: Do the same to each character

Start with message = "Meet At Noon" and an empty new string, coded_message = "" (do not use a list). Loop over every character in message. On each turn, apply the same taught string-method step, character.lower().replace("a", "@"), and concatenate that transformed character onto coded_message. Print the finished new string. Expected output: meet @t noon.

Pattern Spotlight: Identify Do the same to each (map) in your loop. Contrast producing one transformed result for every character with counting only characters that meet a condition.

Real program

After the fixed version works, replace the fixed message with input(). Keep the same character transformation and output; the expected output is for the fixed message only.

How this is checked: Checked by tests that run your code.

Also check yourself

The automatic check cannot see these, so tick each one when your work does it.

For parents and teachers: report a problem

Exercise 14: Find a Letter and Stop Early

Start with letters = "abcdefghijklmnopqrstuvwxyz", target = "m", and found_position = -1. Scan the positions one by one with for position in range(26). Compare the letter at each position with target. When they match, save that position in found_position and use break to stop checking the rest. Print found_position after the loop.

Real program

After the fixed version works, replace the fixed target with input(). Keep the same alphabet scan, early stop, and position output.

How this is checked: Checked by tests that run your code.

Also check yourself

The automatic check cannot see these, so tick each one when your work does it.

For parents and teachers: report a problem

Exercise 15: Count a Letter

Define count_letter(message, letter) to count how many times letter appears in message, using a manual counter instead of .count(). Worked example: count_letter("banana", "a") → 3.

Real program

After the fixed version works, read the message and the letter with separate input() calls. Keep the same manual count and output.

How this is checked: You check this one yourself, against the list below.

The site cannot check this one. Run your program, then tick each item below when your work does it.

Check your work

For parents and teachers: report a problem

Exercise 16: Letters, Spaces, and Marks

Scan the fixed message "go, cat!", keeping three counters for letters (a–z), spaces, and other marks, then print all three totals. Worked example: "go, cat!" → 5 letters, 1 space, 2 marks.

Real program

After the fixed version works, replace the fixed message with input(). Keep the same three counters and output.

How this is checked: You check this one yourself, against the list below.

The site cannot check this one. Run your program, then tick each item below when your work does it.

Check your work

For parents and teachers: report a problem

Exercise 17: First Vowel Position

Scan a message with a manual position counter, stop with break at the first vowel (a, e, i, o, or u), and print its 0-based position. Worked example: "xyzapple" → position 3.

Real program

After the fixed version works, read the message with input(). Keep the same manual position scan, early stop, and output.

How this is checked: You check this one yourself, against the list below.

The site cannot check this one. Run your program, then tick each item below when your work does it.

Check your work

For parents and teachers: report a problem

Exercise 18: Does It Contain a Digit?

Write a function that scans a code and returns a boolean showing whether it contains any digit from 0 through 9. Worked examples: "abc3d" → True, and "abcd" → False.

Real program

After the fixed version works, read both codes with separate input() calls and pass each one to the same function. Keep both computed-label output lines.

How this is checked: You check this one yourself, against the list below.

The site cannot check this one. Run your program, then tick each item below when your work does it.

Check your work

For parents and teachers: report a problem

Exercise 19: Star the Vowels

Build and return a new string with every vowel replaced by *, without using a list. Worked examples: "cat" → "c*t", and "hello" → "h*ll*".

Real program

After the fixed version works, read both messages with separate input() calls and pass each one to the same function. Keep both transformed results on one output line.

How this is checked: You check this one yourself, against the list below.

The site cannot check this one. Run your program, then tick each item below when your work does it.

Check your work

For parents and teachers: report a problem

Exercise 20: Letter-Value Sum

Add the alphabet positions (a = 1 through z = 26) of every letter in a word; find each value by scanning letters = "abcdefghijklmnopqrstuvwxyz" with range(26) and comparing the indexed alphabet letter to the word's character. Worked example: "abc" → 6 (1 + 2 + 3).

Real program

After the fixed version works, read the word with input(). Keep the same alphabet scan, value sum, and output.

How this is checked: You check this one yourself, against the list below.

The site cannot check this one. Run your program, then tick each item below when your work does it.

Check your work

For parents and teachers: report a problem

Exercise 21: Letters That Fit the Budget

Use the word "secret" (values 19, 5, 3, 18, 5, 20) and budget 30; check before adding, adding a letter's alphabet-scan value only if the running total would stay at or below 30, and otherwise stop. Report the number of letters that fit and their value total, then print the fitting prefix with "secret"[:count]. Worked example: 3 letters fit, total 27, prefix "sec".

Real program

After the fixed version works, read the word with input() and the budget with int(input()). Keep the same check-before-adding rule, prefix, totals, and output.

How this is checked: You check this one yourself, against the list below.

The site cannot check this one. Run your program, then tick each item below when your work does it.

Check your work

For parents and teachers: report a problem

Exercise 22: Letters Until the Budget Tips

Use the same word "secret" and budget 30, but use the opposite boundary rule: add then check, stopping as soon as the total exceeds 30. Report how many letters were added, the tipping total, and the tipping letter. Worked example: 4 letters, total 45, tipping letter "r".

Real program

After the fixed version works, read the word with input() and the budget with int(input()). Keep the same add-then-check rule, tipping values, and output.

How this is checked: You check this one yourself, against the list below.

The site cannot check this one. Run your program, then tick each item below when your work does it.

Check your work

For parents and teachers: report a problem

Challenge

Try these after the earlier exercises.

Challenge 1: Case-Insensitive Keyword Check

  • Challenge

Store a message and a keyword in separate variables. Use .lower() on both values and the in operator to check for the keyword without case getting in the way. Print one message when it appears and a different message when it does not. Test with a mixed-case message.

Real program

After the fixed version works, read the message and keyword with separate input() calls. Keep the same case-insensitive check and two possible outputs.

How this is checked: You check this one yourself, against the list below.

The site cannot check this one. Run your program, then tick each item below when your work does it.

Check your work

For parents and teachers: report a problem

Challenge 2: Two-Step Cipher

  • Challenge

Define two_step(message, shift). First reverse the message with [::-1]. Then pass the reversed string to your encode function and return the result. Call it with a lowercase sample message and a fixed integer shift. Describe the two steps your friend must undo to recover the message.

Real program

After the fixed version works, read the message with input() and the shift with int(input()). Keep the same reverse-then-encode computation and output.

How this is checked: You check this one yourself, against the list below.

The site cannot check this one. Run your program, then tick each item below when your work does it.

Check your work

For parents and teachers: report a problem

Back to Secret Codes