Parsing Safely

Real input is messy. Users type spaces, leave fields blank, and enter words where you expected numbers. Safe parsing means checking before you trust.

Checking a number is valid

PYTHON

text = "  42 "
cleaned = text.strip()

if cleaned.isdigit():
    value = int(cleaned)
else:
    value = 0

JAVASCRIPT

const text = "  42 ";
const cleaned = text.trim();
const parsed = Number(cleaned);

const value = Number.isNaN(parsed) || cleaned === ""
  ? 0
  : parsed;
Compare → Both start by trimming whitespace. Python asks the string whether it looks like digits. JavaScript converts first, then checks for NaN, and must also rule out the empty string because Number("") is 0, not NaN.
EXAMPLE
loading editor…
YOUR TURN
Your turn → This is defensive programming: every value is checked before it is trusted. Add a negative number and a decimal to the list and see what each language does.
loading editor…

Syntax has to be exact. Every quote, bracket and parenthesis needs its partner, and in Python the spaces at the start of a line count. One slip and the program won't run; the message will say where.

◈ Graded Challenge

A community fundraiser collected donation amounts from a web form, so every entry is text and some entries are junk. Write a function that takes a list of strings and returns the total of only the valid whole numbers, ignoring anything else. Whitespace should be trimmed before checking.

Name it exactly: def total_donations(entries):

3 visible + 3 hidden
loading editor…

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: Practice Test →
← Back