๐ŸŸก LESSON 04 ยท LESS SCAFFOLDING

Checking Characters

Use isalpha(), isdigit(), and isspace() to inspect strings character-by-character. You write more this time!

๐ŸŸก Less scaffolding โ€” write from hints only, fix trickier bugs

๐ŸŽฏ Learning Objectives

๐Ÿ“ Text File for This Lesson SETUP
Create input.txt: Open Notepad, paste the text below, and save as input.txt in the same folder as your Python file.
TEXT โ€” input.txt
Hello World 123
My phone number is 07700 900123
Python3 is great
No digits here at all
Room 42 is the answer
GCSE grades include 9 8 7 6 5
abc def ghi
Test123Test456
  Spaces at the start and end
Mixed CaSe With 99 Numbers

๐Ÿงช Character Tester ACTIVITY 1

Type any character or word to see what the three functions return!

Try a character or string:

.isalpha()
-
.isdigit()
-
.isspace()
-
.isalnum()
-
๐Ÿ”ฌ Character-by-Character Viewer ACTIVITY 2

See how Python classifies each character in a string. Each box is one character.

Letter (isalpha)
Digit (isdigit)
Space (isspace)
Other

โœ๏ธ Fill in the Gaps ACTIVITY 3

Complete this program that counts letters, digits, and spaces in each line.

for line in input_file:
    line = line.strip()
    letters = 0
    digits = 0
    spaces = 0

    for ch in :
        if ch.:
            letters 1
        elif ch.:
            digits += 1
        elif ch.:
            spaces += 1

    print(f"Letters:{letters} Digits:{digits} Spaces:{spaces}")

๐Ÿ› Fix the Bugs ACTIVITY 4

This code has 4 bugs โ€” some are logic errors, not just syntax! Think carefully.

for line in input_file: line = line.strip() count = 0 for ch in line: if ch.isalpha(): count += 1 if count == 0: print(f"{line} has {count} digit(s)") output_file.write(line , "\\n") input_file.close
Bugs found: 0 / 4

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

Task: Validate & Filter

Write a program that reads input.txt and writes ONLY lines that contain at least one digit to output.txt. Also print the total count of digits found across ALL lines.

You need two loops: an outer for line in file and an inner for ch in line. Keep a running total outside the outer loop.
Use ch.isdigit() inside the inner loop. Set a flag variable (e.g. has_digit = False) and set it True when you find one.

๐Ÿ”ง Subroutines for Character Analysis ACTIVITY 6
๐Ÿ“Œ Why use subroutines here?
When we count letters, digits, and spaces, we repeat the same pattern for every line. A subroutine lets us wrap this logic into a reusable function. We can then call it for any string we want to analyse!
Python โ€” subroutine for character counting
# Define a subroutine to count character types
def count_chars(text):
    letters = 0
    digits = 0
    spaces = 0
    for ch in text:
        if ch.isalpha():
            letters += 1
        elif ch.isdigit():
            digits += 1
        elif ch.isspace():
            spaces += 1
    return letters, digits, spaces

# Define a subroutine to check if a line has digits
def has_digits(text):
    for ch in text:
        if ch.isdigit():
            return True
    return False

# Main program
input_file = open("input.txt", "r")
output_file = open("output.txt", "w")

for line in input_file:
    line = line.strip()
    l, d, s = count_chars(line)
    print(f"{line} โ†’ Letters:{l} Digits:{d} Spaces:{s}")

    if has_digits(line):
        output_file.write(line + "\n")

input_file.close()
output_file.close()
print("Done! Lines with digits saved to output.txt")
๐Ÿ”‘ New concept: returning multiple values!
โ€ข return letters, digits, spaces โ€” returns 3 values at once
โ€ข l, d, s = count_chars(line) โ€” unpacks the 3 returned values into 3 variables
โ€ข The has_digits() function returns True/False โ€” useful in an if statement
๐Ÿง  Quick Quiz ACTIVITY 7
What does "abc123".isalpha() return?
True
False โ€” it contains digits too
3
An error
If ch = "7", which returns True?
ch.isalpha()
ch.isdigit()
ch.isspace()
None of them
How do you loop through each character in a string called word?
for i in len(word):
for ch in word:
for ch in word.split():
while word:
What does " ".isspace() return?
False
True
1
None

๐Ÿ”ฎ Predict the Output ACTIVITY 8

What does each snippet print? Think carefully about character types!

What does this print?
text = "abc123"
print(text.isalpha())
True
False
3
An error
What does this print?
def has_digits(text):
    for ch in text:
        if ch.isdigit():
            return True
    return False

print(has_digits("Hello World"))
True
False
0
An error
What does this print?
word = " "
print(word.isspace())
print(word.isalpha())
True
False
False
True
True
True
False
False

๐Ÿš€ Extension Activity STRETCH

Challenge: Password Validator Subroutine

Write a program with a subroutine called validate_password(password) that checks if a password is strong. A strong password must:

โ€ข Be at least 8 characters long (use len())
โ€ข Contain at least one letter (use isalpha())
โ€ข Contain at least one digit (use isdigit())

The subroutine should return True if the password is strong, False if not.

Read passwords from input.txt (one per line) and write only the strong passwords to output.txt. Print how many passed and how many failed.

Inside the subroutine, use variables like has_letter = False and has_digit = False. Loop through each character with for ch in password. At the end, return len(password) >= 8 and has_letter and has_digit.
โ† Lesson 3 Lesson 5: Combining It All โ†’