๐ŸŸก LESSON 03 ยท SOME SCAFFOLDING

Finding & Searching

Use .find() to search inside strings and the in operator to check membership. You write more code this lesson!

๐ŸŸก Part code provided โ€” fix bugs and write sections yourself

๐ŸŽฏ Learning Objectives

๐Ÿ” .find() Live Explorer ACTIVITY 1

Type a word to search for inside a string. See exactly how .find() works!

sentence = "The cat sat on the mat in Jersey"


๐Ÿ“Œ Key facts about .find():
โ€ข Returns the index position of the first match
โ€ข Returns -1 if the substring is not found
โ€ข It is case-sensitive โ€” "cat" โ‰  "Cat"
โ€ข Syntax: position = my_string.find("search_word")
๐Ÿ“ 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
The island of Jersey is beautiful
Python is a great programming language
I love computer science at school
Jersey has amazing beaches and cliffs
My favourite subject is not island studies
Programming in Python makes me happy
The Channel Islands include Jersey and Guernsey
GCSE exams start in May
โœ๏ธ Fill in the Gaps ACTIVITY 2

Complete the code. This time you have fewer hints โ€” think carefully!

for line in input_file:
    line = line.strip()

    # Check if "Python" appears anywhere in the line
    if "Python" in :
        print("Found Python in:", line)

    # Use .find() to get the position of "a"
    pos = line.

    # Only print if "a" was found (not -1)
    if pos -1:
        print(f"Found 'a' at position {pos}")

๐Ÿ› Fix the Bugs ACTIVITY 3

This code has 3 bugs. Click each underlined section to reveal the fix.

input_file = open("input.txt", "r") output_file = open("output.txt", "w") for line in input_file: line = line.strip() pos = line.find Jersey if pos == -1: print("Jersey found at:", pos) output_file.write(line) input_file.close() output_file.close()
Bugs found: 0 / 3

๐Ÿ–Š๏ธ Write Your Own Code ACTIVITY 4

Task: Search and Filter

Write a Python program that reads input.txt and writes only the lines that contain the word "island" (case-insensitive โ€” hint: convert to lower first!) to output.txt. Print how many matching lines were found.

Convert to lowercase first: line.lower() then use if "island" in line_lower:
Use a counter variable: count = 0 before the loop, then count += 1 each time you find a match.

๐Ÿ”ง Using Subroutines (Functions) ACTIVITY 5
๐Ÿ“Œ What is a subroutine?
A subroutine (also called a function) is a reusable block of code that performs a specific task. In Python, we create subroutines using the def keyword. This helps us:
โ€ข Avoid repeating code โ€” write once, use many times
โ€ข Organise our program โ€” break it into smaller, named blocks
โ€ข Make code easier to read โ€” each function has a clear purpose
Python โ€” using subroutines
# Define a subroutine to search for a word in a line
def search_line(line, keyword):
    position = line.lower().find(keyword.lower())
    if position != -1:
        print(f"Found '{keyword}' at position {position} in: {line}")
        return True
    else:
        return False

# Main program โ€” uses the subroutine
input_file = open("input.txt", "r")
count = 0

for line in input_file:
    line = line.strip()
    if search_line(line, "Jersey"):
        count += 1

print(f"\nTotal matches: {count}")
input_file.close()
๐Ÿ”‘ Key points about subroutines:
โ€ข def search_line(line, keyword): โ€” defines a function with parameters
โ€ข return True โ€” sends a value back to where the function was called
โ€ข search_line(line, "Jersey") โ€” calls the function with arguments
โ€ข The function can be called many times with different keywords!
๐Ÿง  Quick Quiz ACTIVITY 6
What does s = "hello"; s.find("ll") return?
1
2
True
-1
What does "cat".find("dog") return?
False
0
-1
None
Which expression checks if "Python" appears in line?
line.find() == "Python"
"Python" in line
line.contains("Python")
line == "Python"
Is .find() case-sensitive? What does "Hello".find("hello") return?
0 โ€” it ignores case
-1 โ€” it IS case-sensitive
True
5

๐Ÿ”ฎ Predict the Output ACTIVITY 7

What does each snippet print? Think carefully before clicking!

What does this print?
sentence = "I love Python"
pos = sentence.find("love")
print(pos)
0
2
4
True
What does this print?
word = "Hello"
print("hello" in word)
True
False
0
An error
What does this print?
def check(text, word):
    return word in text.lower()

result = check("Hello World", "hello")
print(result)
True
False
hello
An error

๐Ÿš€ Extension Activity STRETCH

Challenge: Multi-Keyword Search with Subroutine

Write a program that uses a subroutine to search for multiple keywords in each line of input.txt. The subroutine should take a line and a keyword, and return True/False.

Your program should:

1. Define a def search(line, keyword) subroutine
2. Ask the user for 3 different keywords using input()
3. Read each line from input.txt
4. Call the subroutine for each keyword on each line
5. Write matching lines to output.txt with which keyword was found
6. Print a summary: how many matches for each keyword

Use three counter variables (one per keyword). Call your search function three times per line โ€” once for each keyword. Use line.lower() inside the subroutine for case-insensitive matching.
โ† Lesson 2 Lesson 4: Checking Characters โ†’