Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 5.4 — Keyword-Only and Positional-Only Parameters
Python · Example 1 of 2

Keyword-only parameters

The failing call is caught and its error is printed. try runs a risky line, and if it fails, the except part runs instead of stopping the program (Topic 7.1 teaches it). Read the message: it says one positional argument was allowed.

A bare * in a signature makes every parameter after it keyword-only, and a / makes every parameter before it positional-only (/ arrived in Python 3.8). They let a function's author decide how callers may pass each argument, which keeps APIs readable and flexible to change.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write describe(name, *, age=0, city="unknown") that returns text like Asha, 12, Pune. Show a valid call, and show that passing the age positionally raises TypeError.

02

Write half(x, /) that returns x / 2. Show that half(x=10) raises TypeError.

03

Use inspect.signature to print the signatures of round and len. Which of the two lets you pass its first argument by name?

Explain it without notes

01

What do * and / mean in a parameter list?

02

Give two reasons to make a parameter positional-only.

03

Why are boolean flags usually best as keyword-only?

04

What is the full left-to-right order of parameter kinds in a signature?

Keyword-only parameters
Sign in to run this example in your browser.

Expected output

http://example.com:80
https://example.com:8080
TypeError: connect() takes 1 positional argument but 2 were given
6
106