Paul's Python CoursePPC

Defensive input

Not met yet

Don't trust input, whether a person typed it or a machine wrote it. Tidy it first, with .strip() and .upper(), check it's the shape you need, and decide what happens when it isn't: ask again, skip it and say so, or stop with a clear message. Never carry on quietly with a wrong value.

Try it

main.py

When it asks, try typing "deep", "-3", " 4.5 ".

def ask_depth():
    while True:
        text = input("Depth in metres? ").strip()
        try:
            depth = float(text)
        except ValueError:
            print("That isn't a number.")
            continue
        if depth < 0:
            print("Depths aren't negative.")
            continue
        return depth


print(ask_depth())

Output

Press Run and what your program prints shows up here.

Easy to get wrong

  • Thinks input arrives without stray spaces or odd capitals, so it can be compared exactly as it is.
  • Thinks quietly ignoring bad input, or swapping in a default, is as good as refusing it and saying so.

Where it comes up