Menu
CoddyTech

Defaults and Named Arguments

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

Go calls are positional and ordinary Go parameters have no defaults. Python parameters can have defaults and callers can name arguments in a different order. The caller must not bind a parameter twice, whether positionally or by keyword. Use keyword arguments for clarity rather than building an options map when the API already names the options. Default expressions are evaluated once when the def statement executes.

Go

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

func cost(price, quantity int) int { return price * quantity }
// Inside main:
fmt.Println(cost(5, 1))
fmt.Println(cost(5, 3))

Python

def cost(price, quantity=1):
    return price * quantity
print(cost(5))
print(cost(quantity=3, price=5))

Porting trap

A mutable default list is shared between calls. Use a None default and allocate a new list inside when each omitted argument should get fresh state. Go has no matching default-parameter mechanism.

challenge icon

Challenge

Beginner

Implement line_cost(price, quantity=1, discount=0), returning integer price * quantity - discount. Inputs are nonnegative and discount is at most the product. The driver reads price, quantity, and discount, calls once with price only, once with two positional arguments, and once with reordered keyword arguments, then prints the results. Go has no ordinary parameter defaults or named call arguments; implement the Python signature and binding rules exactly.

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 line_cost

price = int(input())
quantity = int(input())
discount = int(input())
print(line_cost(price))
print(line_cost(price, quantity))
print(line_cost(discount=discount, price=price, quantity=quantity))
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