Menu
CoddyTech

Star Arguments and Unpacking

Lesson 24 of 48 in Coddy's Python for C# Developers course.

Collect and expand positional and keyword arguments.

C# reference excerpt

Executable statements use C# top-level program style; type-only examples are declarations. System names assume the usual using System directive.

static int Sum(params int[] values) {
    int total = 0;
    foreach (int value in values) total += value;
    return total;
}
Console.WriteLine(Sum(2, 3));

Python

def total(*values, **options):
    return sum(values) * options.get("factor", 1)

print(total(2, 3, factor=2))

What changes

*values collects extra positional arguments as a tuple, whereas C# params int[] collects an array of that declared element type. **options collects keyword arguments in a dictionary. At a call, *sequence expands positional arguments and **mapping expands string-keyed keyword arguments. There is no direct C# params equivalent to arbitrary keyword collection.

Transfer mistake

Passing a list as one argument is different from expanding it. Duplicate values for one named parameter raise TypeError rather than selecting an overload.

Your task

Implement scaled_total(*values, **options). Sum the integer positional values and multiply by options.get("factor", 1); ignore other keyword names. Do not mutate supplied collections. The driver reads an integer-token line, possibly empty, then a factor. It prints one call using only expanded values and one using expanded values plus a keyword dictionary.

challenge icon

Challenge

Beginner

Implement scaled_total(*values, **options). Sum the integer positional values and multiply by options.get("factor", 1); ignore other keyword names. Do not mutate supplied collections. The driver reads an integer-token line, possibly empty, then a factor. It prints one call using only expanded values and one using expanded values plus a keyword dictionary.

Editable implementation files: functions.py. The locked driver.py is the supplied launcher or input/output harness and must remain unchanged.

Keep the supplied imports and exact API names. Return results or raise the required exceptions; do not read input or print from these implementation modules.

Try it yourself

from functions import scaled_total

values = [int(part) for part in input().split()]
factor = int(input())
print(scaled_total(*values))
print(scaled_total(*values, **{"factor": factor, "note": "ignored"}))
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Python for C# Developers

Practice on your own: Online Python compiler