HomeCourseModule 04 › Putting it together — a mini contact-cleaner

Putting it together — a mini contact-cleaner

Module 04 · Control Flow8 min readBeginner

What you'll learn

  • Combine the four control-flow tools in one script
  • Read a tiny piece of real-feeling input
  • Produce a clean output

The goal

You receive a list of contacts where each item looks like one of these:

raw = [
    "  Alice Smith,alice@example.com,42  ",
    "Bob Brown,BOB@EXAMPLE.com,",     # missing age
    "carol,wrong-email,29",            # no last name, bad email
    ",dave@example.com,55",            # no name
    "  Eve  Wells, EVE@example.com , 31 ",
]

You want a clean list of dicts with valid contacts only.

Walkthrough

Step 1: split the line and trim each piece

cleaned = []
for line in raw:
    parts = [p.strip() for p in line.split(",")]
    cleaned.append(parts)

Step 2: validate name, email, age

contacts = []
for name, email, age_text in cleaned:
    if not name:                       continue       # need a name
    if "@" not in email:               continue       # need an @
    try:
        age = int(age_text)
    except ValueError:
        age = None
    contacts.append({
        "name":  name.title(),
        "email": email.lower(),
        "age":   age,
    })

Step 3: inspect

for c in contacts:
    print(c)

Output:

{'name': 'Alice Smith', 'email': 'alice@example.com', 'age': 42}
{'name': 'Bob Brown',   'email': 'bob@example.com',   'age': None}
{'name': 'Eve  Wells',  'email': 'eve@example.com',   'age': 31}

Carol got dropped (bad email) and Dave got dropped (no name). Bob made it in with a None age. Real data, real result.

Key takeaways

  • Real-world scripts always chain these tools — loops + comprehensions + ifs + try/except.
  • Validation is just "skip if not what we want" (continue) and "guess if we can" (try/except).
  • Clean inputs at the door; the rest of your code stays simple.

Add a feature

Extend the cleaner: also reject contacts under age 18. Add a counter for how many were rejected and print it at the end.

📹 Video walkthrough
A video walkthrough of this lesson will be embedded here. Until then, the written walkthrough above mirrors what the video will cover step-for-step.