Conversion, booleans & finite numbers

Validate a score with intention

Lesson 17 of 20 · 12 min · Module 6: Reliable inputs & practical reports

Converting a value is only the first step. A valid score must also be finite and inside the accepted range.

Start this lesson →

Free. No installation: you write and run the code in your browser, and it is checked automatically.

By the end, you’ll be able to…

  • Validate both type and meaning
  • Use a narrow exception handler

The idea

Use float for numeric conversion and math.isfinite to reject infinity and NaN. Python booleans act like integers in many numeric contexts, so reject them explicitly when they are not meaningful scores.

import math
print(float(" 75.5 "))
print(math.isfinite(float("inf")))

01Define acceptable sources

This contract permits numeric strings but rejects booleans. Make that decision explicit before relying on automatic numeric behavior.

02Handle conversion separately

Conversion can fail even for an allowed source type. A narrow except documents this expected failure without hiding unrelated bugs.

03Inspect the converted number

The text inf converts successfully, but is not a useful score. A successful conversion is not the end of validation.

Your turn

Write normalize_score(value). Accept an int, float, or numeric string representing a finite score from 0 to 100 inclusive. Return it as a float. Return None for booleans, invalid types, failed conversions, nonfinite values, or values outside the range.

What the checks look for

  • Accepts numeric values and trimmed numeric text
  • Rejects booleans and unrelated shapes
  • Rejects failed conversion and nonfinite values
  • Enforces both boundaries
Try it in the editor →

Take this with you

Validation is a sequence of distinct questions, not just a try/except wrapper.

Go a little further

Add a function that reports a reason for rejection without changing normalize_score’s return contract.

Learn Python Foundations for free

20 short lessons with real code and instant checks.

See the whole course →