Menu
CoddyTech

Variadics and Keyword Options

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

Go variadic parameters collect values into a slice, and a slice can be expanded with a trailing ... at the call. Python *values collects positional extras into a tuple; **options collects named extras into a dictionary. At a call, * expands an iterable and ** expands a mapping with string keys. A Python function can accept both forms. This is call binding, not an implicit merge policy for duplicated keywords.

Go

Go excerpt: declarations above main, statements inside main. Imports: fmt. The verification bundle contains the complete program.

func total(values ...int) int { result := 0; for _, n := range values { result += n }; return result }
// Inside main:
values := []int{2, 3}
fmt.Println(total(values...))

Python

def total(*values, **options):
    return sum(values) * options.get("factor", 1)
values = [2, 3]
print(total(*values))
print(total(*values, **{"factor": 4}))

Porting trap

Calling f(x=1, **{"x": 2}) raises TypeError because x is bound twice. Python does not silently let the mapping overwrite the explicit keyword.

challenge icon

Challenge

Beginner

Implement scaled_total(*values, **options). Return the sum of integer values times options.get("factor", 1), ignoring other option names. Do not mutate inputs or print. The driver reads integer tokens (possibly none), then a factor, and prints results from an unpacked positional call and a call with unpacked factor options. Go variadic parameters form a slice; Python positional extras form a tuple and keyword extras form a dictionary.

Editable files: functions.py. Keep the provided imports and the required API names. The locked driver.py supplies execution and checks; do not edit it.

Implement the named definitions in the editable modules without input or printing. The driver owns input/output and may call the APIs again on fresh data without producing extra output.

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 Go Developers

Practice on your own: Online Python compiler