Pattern Matching in Text

A free sample lesson from AI Basics

The idea

A detective's magnifying glass scanning a whole page of text for one exact clue - it doesn't matter where on the page the clue is, only that it's there somewhere.

What it actually is

Pattern matching means checking if a specific word or phrase appears inside a larger piece of text - Python's in operator does exactly this. It's the very first building block behind how simple chatbots 'understand' what you typed.

How you write it

if "keyword" in text:
    ...

A worked example

message = "hello there, how are you?"
if "hello" in message:
    print("Greeting detected!")

"hello" in message checks whether that exact text appears ANYWHERE inside message - it does, right at the start, so the condition is true.

message = "HELLO THERE"
if "hello" in message.lower():
    print("Greeting detected!")

Without .lower(), this would fail - "hello" in "HELLO THERE" is False, because in is case-sensitive. Converting the message to lowercase first makes the check work no matter how the user typed it.

Mistakes children actually make

Mistake 1: forgetting .lower() - "hello" in "Hello there" is actually False (capital H doesn't match lowercase h), so always lowercase both sides for real word matching. Mistake 2: expecting in to match a WHOLE WORD only - "cat" in "category" is actually True, since in matches ANY substring, not just whole separate words - a real gotcha for keyword-based bots. Mistake 3: confusing in with == - message == "hello" checks if the ENTIRE message is exactly that word, while "hello" in message checks if it appears anywhere inside a longer message; for scanning real sentences, in is almost always the one you want.

Then they try it

In the app this lesson continues with the animated explanation, spoken aloud, and then the practice: Check if the word "help" appears anywhere in the message (case-insensitively) and print "Detected a request for help!" if so. The editor runs your child’s real code and checks the result, with their coding buddy reacting to what they wrote.

Try it free