Menu
CoddyTech

Named Arguments and Defaults

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

Use named arguments and defaults without sharing accidental mutable state.

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 Cost(int price, int quantity = 1) { return price * quantity; }
Console.WriteLine(Cost(quantity: 3, price: 4));

Python

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

print(cost(quantity=3, price=4))

What changes

C# uses name: value at a call; Python uses name=value. Both support omitted optional arguments, but Python default expressions are evaluated once when def executes. C# optional defaults have restricted constant/default-value forms; an arbitrary new List<int>() is not an optional parameter default. For a fresh Python list per call, use None as the default and create [] inside.

Transfer mistake

def collect(items=[]) shares one list between calls. Also, Python does not choose method overloads by signature: defining the same function name again rebinds that name.

Your task

Implement line_cost(price, quantity=1, discount=0), returning price * quantity - discount. Inputs are nonnegative integers and discount is no larger than the product. The driver reads three lines and checks calls with price only, two positional arguments, and reordered named arguments, printing each result. Preserve the exact parameter names and defaults.

challenge icon

Challenge

Beginner

Implement line_cost(price, quantity=1, discount=0), returning price * quantity - discount. Inputs are nonnegative integers and discount is no larger than the product. The driver reads three lines and checks calls with price only, two positional arguments, and reordered named arguments, printing each result. Preserve the exact parameter names and defaults.

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 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 C# Developers

Practice on your own: Online Python compiler