0%

More Expressive Functions · practice

Optional Values and None

In the previous lesson, False was a real setting. It meant that a particular kind of cleaning should not happen. That is different from not supplying a choice at all.

Some optional need to distinguish between two situations:

  • no was supplied, so the should choose one;

  • a value was supplied, so the function should preserve it.

Python’s None gives us a clear way to represent the first situation:

def build_feedback(score, total, note=None):
    if note is None:
        note = "Keep practicing."
    return f"{score}/{total}: {note}"

Here, note=None does not mean that every note must be None. It means that note starts as None when the function is called without that :

build_feedback(6, 10)

Code can still provide a note when it has one:

build_feedback(10, 10, note="Perfect score!")

The function replaces None with its own message but leaves a supplied note alone.

Check identity with is None

To ask whether the note was omitted, check for that one exact value:

if note is None:

None is one specific value, so identity is the clearest check. A truthiness check would be broader:

if not note:

As you learned in Fundamentals I, None, "", 0, and False are all falsy. That broader would treat all of them as absent, even when the code calling the function supplied one intentionally.

For example, an empty can deliberately request no message:

build_feedback(8, 10, note="")

The empty string was supplied. Replacing it with default feedback would ignore the caller’s choice.

Why is if note is None better than if not note for this optional note?

Supply feedback only when absent

Complete build_feedback by turning this distinction into code. Choose a message only when note is None; otherwise preserve the supplied string, including an empty one.

Task

Complete build_feedback.

  • If note is None, use "Perfect score!" when score == total.

  • Otherwise, when note is None, use "Keep practicing.".

  • If the caller supplies a note, preserve it exactly, even when it is "".

  • Return score/total: note.

Do not print inside the .