Learning route
Index carefully. Build a new string. Test what the user can actually type.
Prerequisite: Can index a list, trace a loop and use a function with a returned value. Follow Lessons 03–04 first if needed.
- Use length, indexing, slicing and case conversion correctly.
- Validate length before indexing an input string.
- Distinguish a digit’s numeric value from its character code.
- Build a new string with concatenation and verify normal and invalid cases.
Retrieve and explain
- What are the valid non-negative indices for a list of length 4?
- What does
len("code")return? - Why can
input()preserve a leading zero that int() removes? - State what a returned value allows a caller to do.
A string is an ordered sequence of characters. Indexing selects one character; slicing selects a substring. In text[start:stop], the start is included and the stop is excluded.
word = "Python"
print(len(word))
print(word[0])
print(word[1:4])
print(word.upper())
print(word)
| Expression | Result | Reason |
|---|---|---|
| len(word) | 6 | Six characters. |
| word[0] | P | First character. |
| word[1:4] | yth | Indices 1, 2 and 3. |
| word.upper() | PYTHON | Returns a converted string. |
| word afterwards | Python | The original binding was not reassigned. |
Strings are immutable: individual characters cannot be changed with word[0] = "p". Build or assign a new string instead. text.lower() changes case in its return value; text.strip() returns text with surrounding whitespace removed.
print(int("7"))
print(ord("7"))
print(chr(55))
The outputs are 7, 55 and 7. int("7") is a numeric conversion. ord("7") is the character code. chr(55) returns a one-character string. The first 128 Unicode code points match ASCII.
Check before indexing.
text[0] raises IndexError when text is empty. Check the length first. A slice such as text[:2] may return fewer than two characters without raising an error, so slicing alone is not validation.
Worked example
Create a badge from a non-empty first name: trim surrounding spaces, convert to uppercase, take up to the first three characters and attach the name’s length. A blank result after trimming returns Invalid name.
def make_badge(raw_name):
clean_name = raw_name.strip().upper()
if len(clean_name) == 0:
badge = "Invalid name"
else:
badge = clean_name[:3] + str(len(clean_name))
return badge
print(make_badge(" Asha "))
| Stage | Value |
|---|---|
| Raw input | " Asha " |
| After strip and upper | "ASHA" |
| Length | 4 |
| Slice [:3] | "ASH" |
| Combined result | "ASH4" |
A short name such as Li becomes LI2. An empty or whitespace-only input is rejected before further processing. The badge rules here are illustrative, not a secure identifier system.
Repair practice
The intended program prints a person’s uppercase initial, or No name for blank input. Diagnose and repair both problems.
name = input("Name: ").strip()
name.upper()
initial = name[0]
if len(name) == 0:
print("No name")
else:
print(initial)
Test asha, an empty line and three spaces. Explain why moving only the if statement is not enough.
Repair feedback
name = input("Name: ").strip()
if len(name) == 0:
print("No name")
else:
name = name.upper()
initial = name[0]
print(initial)
The original indexes before checking for emptiness, so blank input crashes. It also discards the returned uppercase string. Correct results: A, No name, No name. Accept name[0].upper() after the non-empty check.
Independent practice
Independent build: club reference. Read a code, remove surrounding whitespace and convert letters to uppercase. A valid code has exactly five characters: the prefix PA followed by three ASCII digits. Keep leading zeros.
- Use a function
normalise_code(raw_code)that returns the cleaned uppercase string. - Check its length before inspecting the prefix and suffix.
- Check every suffix character against
"0123456789". - For valid input, output Valid: and the code, then Digit total: and the sum of the three numeric digits.
- For invalid input, output only Invalid code.
Test pa007, PA123, PA999, PA12, PB123, PA1X3 and empty input. Here the digit total uses int(), not ord().
# Proof Academy | Lesson 05 | Club reference
# Valid format after trimming and uppercasing: PA + 3 ASCII digits.
def normalise_code(raw_code):
# Your task: return the cleaned, uppercase text.
pass
raw_code = input("Club reference: ")
# Your task: call normalise_code, then validate length/prefix/digits.
# Your task: valid -> display the code and numeric digit total.
# Your task: invalid -> display Invalid code only.
Model program and marking guidance
# Proof Academy | Lesson 05 | Worked solution
def normalise_code(raw_code):
return raw_code.strip().upper()
raw_code = input("Club reference: ")
club_code = normalise_code(raw_code)
valid = False
if len(club_code) == 5:
if club_code[:2] == "PA":
valid = True
for character in club_code[2:]:
if character not in "0123456789":
valid = False
if valid:
total = 0
for character in club_code[2:]:
total = total + int(character)
print("Valid:", club_code)
print("Digit total:", total)
else:
print("Invalid code")
- Function returns trimmed uppercase input and main calls it. [1]
- Enforces exactly five characters. [1]
- Checks the PA prefix. [1]
- Accepts only ASCII digits in all three suffix positions. [1]
- Sums numeric digit values, not character codes. [1]
- Preserves leading zeros in the displayed valid code. [1]
- Outputs only an error for invalid input; no unsafe conversion. [1]
- Records expected and actual results for all seven specified cases. [1]
Exam practice
Original Proof Academy practice · 6 marks. Use label = "Code07".
- State
len(label). [1] - State
label[1:4]. [1] - Write an expression that returns the lowercase version. [1]
- Explain why
label[6]fails. [1] - State
int(label[4:])andord(label[4]). The ASCII code of 0 is 48. [2]
Worked feedback
6 (1); ode (1); label.lower() (1); the final non-negative index is 5, so 6 is out of range (1); 7 (1) and 48 (1). The numeric conversion removes a leading zero, but the character-code operation describes the character itself.
Homework and feedback
30 minutes: 5 minutes retrieval, 15 minutes implementation, 10 minutes tests.
Write initials(full_name). For this task the input contains exactly two non-empty ASCII-letter words separated by a single space, with no spaces at either end. Return uppercase initials separated by a full stop. Use split(" ") to obtain the two words. Test “asha patel”, “Li Wu” and “BEN COLE”. Then explain which assumptions would need to change for names with more than two words.
Homework feedback
def initials(full_name):
parts = full_name.split(" ")
result = parts[0][0].upper() + "." + parts[1][0].upper()
return result
print(initials(input("Two-word name: ")))
Results: A.P, L.W and B.C. This deliberately constrained task does not handle empty input or multiple spaces. A broader specification would need rules for additional words and spacing before safe indexing.
Sources and further practice
This chapter is written for Pearson Edexcel GCSE Computer Science 1CP2. Use the specification references in the chapter heading to locate the relevant requirements. Practice questions and point allocations on this page are original Proof Academy teaching material unless a question is explicitly identified as a sourced past-paper bridge.
- Pearson Edexcel 1CP2 specification
- PMT Paper 1 papers and mark schemes
- PMT Paper 2 papers and mark schemes
When using an original paper, open its matching mark scheme and supplied coding files where required. Use that paper's instructions and marks. A short classroom exercise is not a substitute for a full official task.
Trace lab · inline, no inner scroll
Name badge
Trim, uppercase, take up to three characters, then append the cleaned length.
Keep your evidence
Export your notes before changing devices.
Notes stay in this browser. The Quiz tab records the chapter check, and Resources holds the long-answer questions.