๐Ÿ”ด LESSON 05 ยท MOSTLY INDEPENDENT

Combining It All

Put all string functions together in one program. You write the code โ€” only light hints available. The reference card below is your main support.

๐Ÿ”ด You write the code โ€” hints on request only

๐ŸŽฏ Learning Objectives

โœ… Task Completion Tracker

0 / 5 tasks completed
๐Ÿ“– String Functions Reference USE THIS!
s.upper()
Returns string in ALL CAPS
s.lower()
Returns string in all lowercase
len(s)
Returns number of characters
s.find("x")
Returns index of "x" or -1
s[0]
First character (index 0)
s[-1]
Last character
s[0:3]
Characters at index 0, 1, 2
s.isalpha()
True if ALL letters
s.isdigit()
True if ALL digits
s.isspace()
True if all whitespace
"x" in s
True if "x" is in s
s.strip()
Remove leading/trailing whitespace

๐Ÿ’ป Coding Tasks WRITE YOUR OWN
๐Ÿ“ Create input.txt for this lesson: Open Notepad, paste the text below, and save as input.txt in the same folder as your Python file.
TEXT โ€” input.txt
Python is a versatile language
Jersey has a population of 103000
GCSE Computer Science exam is 1CP2
I scored 95 percent on my test
the quick brown fox jumps
Programming helps solve problems
My postcode is JE2 3AB
There are 365 days in a year
Hello World
Channel Islands include Jersey and Guernsey
Room 101 is down the corridor
abcdefghijklmnopqrstuvwxyz
TASK 01

๐Ÿ“Š Line Statistics

Write a program that reads every line and writes to output.txt a report showing each line's: original text, length, first character, last character, and an uppercase version. Format it clearly.

Use an f-string: output_file.write(f"Line: {line} | Len: {len(line)} | First: {line[0]}\n")
Structure: open both files โ†’ for line in input: strip, process, write โ†’ close both
TASK 02

๐Ÿ” Keyword Search

Extend your program (or write a new one) that searches each line for a keyword that the user types. Only write lines containing that keyword to output.txt. Print how many matches were found. Make the search case-insensitive.

Convert both: if keyword.lower() in line.lower():
TASK 03

๐Ÿ“ˆ Character Analyser

Write a program that reads the file and for each line counts: number of letters, number of digits, number of spaces. Write a summary line to output.txt for each line. At the end print totals across the whole file.

Before the outer for loop, set: total_letters = 0, then inside the loop add: total_letters += letters
TASK 04

๐Ÿ”ง Refactor with Subroutines

Take your Task 03 code and refactor it to use subroutines. Create at least two functions:

1. def count_chars(line) โ€” takes a string, returns the count of letters, digits, and spaces
2. def format_report(line, letters, digits, spaces) โ€” takes the data and returns a formatted string for the output file

In Python you can return multiple values: return letters, digits, spaces and unpack them: l, d, s = count_chars(line)
Use an f-string: return f"Line: {line} | Letters: {letters} | Digits: {digits} | Spaces: {spaces}\n"

๐Ÿ› Fix the Bugs ACTIVITY 4 โ€” NO HINTS

This code has 5 bugs. Find them all โ€” no clue which lines they're on this time. Click underlined text to fix.

input_file = open("input.txt", "a") output_file = open("output.txt", "w") total = 0 for line in input_file: line = line.strip letters = 0 for ch in line: if ch.isalpha(): letters = 1 total += letters if letters < 5: result = upper(line) output_file.write(result + "\n") print("Total letters:", total) input_file.close() output_file.close()
Bugs found: 0 / 5

๐Ÿง  Stretch Quiz ACTIVITY 5
What is the output of this code?
s = "hello"
print(s[1:4].upper())
"HELLO"
"ELL"
"ELO"
"ell"
Which line correctly counts digits in a string s?
count = s.isdigit()
count = s.count(digit)
count = sum(1 for ch in s if ch.isdigit())
count = len(s.isdigit())
What does " hello ".strip().upper()[0] return?
" "
"h"
"H"
An error

๐Ÿ”ฎ Predict the Output ACTIVITY 6

These snippets combine multiple string functions. What does each one print?

What does this print?
def process(text):
    return text.strip().upper()[0:5]

print(process(" hello world "))
HELLO
hello
HELLO WORLD
HEL
What does this print?
line = "Test123"
count = 0
for ch in line:
    if ch.isdigit():
        count += 1
print(count)
1
3
7
4
What does this print?
word = "Python"
result = word.lower().find("th")
print(result)
0
1
2
-1
What does this print?
def count_chars(text):
    letters = 0
    digits = 0
    for ch in text:
        if ch.isalpha(): letters += 1
        elif ch.isdigit(): digits += 1
    return letters, digits

l, d = count_chars("Hi 42!")
print(f"{l} letters, {d} digits")
2 letters, 2 digits
3 letters, 2 digits
2 letters, 1 digits
5 letters, 0 digits

๐Ÿš€ Extension Activity STRETCH
TASK 05 โ€” EXTENSION

Challenge: Text Statistics Dashboard

Write a complete program using at least 3 subroutines that produces a detailed text statistics report. Your program should include:

1. def count_chars(line) โ€” counts letters, digits, spaces
2. def find_longest_word(line) โ€” finds the longest word in a line (hint: use .split())
3. def generate_summary(total_lines, total_letters, total_digits, longest_line) โ€” returns a formatted summary string

Read input.txt and write a full report to output.txt. The report should include per-line stats AND an overall summary at the end with totals and the longest line found.

Split the line into words: words = line.split(). Then loop through and compare lengths: if len(word) > len(longest): longest = word
โ† Lesson 4 Lesson 6: Final Challenge โ†’