0%

More Expressive Functions · practice

Positional and Keyword Arguments

The previous lesson gave a a default . That made this shorter call possible:

format_score(7, 10)

Python still needs to know which value belongs to which parameter. This lesson looks at the two ways we can make that connection.

Consider a that describes one quiz attempt:

def describe_attempt(learner, score, total, status="complete"):
    ...

The names learner, score, total, and status are parameters. They belong to the function definition. When we call the function, the values we supply are called .

Let the order carry the meaning

In this call, the arguments are not named:

describe_attempt("Mina", 8, 10)

Python uses their positions. The first value, "Mina", belongs to the first parameter, learner. The next two values become score and total. Arguments supplied this way are called positional arguments.

This works well when there are only a few values and their meaning is easy to recognize. Adding one more makes the call less obvious:

describe_attempt("Mina", 8, 10, "needs review")

The code works, but a reader may have to return to the function definition to discover what "needs review" means.

Name an argument where you call the function

We can write the parameter name together with the value:

describe_attempt("Mina", 8, 10, status="needs review")

Writing status= makes the purpose of the final string visible right where the function is called. This is a keyword argument.

We can also name every argument:

describe_attempt(
    learner="Mina",
    score=8,
    total=10,
    status="needs review",
)

Both styles call the same function. Positional arguments keep short, familiar calls compact. Keyword arguments are useful for optional choices and for values whose purpose would otherwise be difficult to guess.

When a call mixes the two styles, positional arguments must come first. After the first keyword argument, every remaining argument must also be named.

Which call most clearly changes only the optional status?

Try both styles

The function in the editor is already complete. Build a named reports with two calls so you can practice choosing how each argument is supplied:

  1. Use positional arguments for Mina’s name, score, and total. Let the default status apply.

  2. Use Noah’s name positionally, then use keyword arguments for score, total, and status.

The first call uses the default introduced in the previous lesson. The second makes Noah’s unusual status visible by naming it.

Task

Replace the empty reports with two calls to describe_attempt.

  • Mina scored 8 out of 10. Let the default status apply.

  • Noah scored 6 out of 10 and has the status "needs review".

  • For Noah, pass score, total, and status by keyword.

Keep the provided that prints each report.