Menu
CoddyTech

Defaults and Named Arguments

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

C functions have positional arguments and no language-level default parameters. A C wrapper can supply a common quantity explicitly; Python can express that default in the function definition. Python callers may use positional arguments followed by keyword arguments, and keywords name parameters rather than positions. Omitted arguments use stored defaults. Defaults are evaluated once when the def statement executes, not separately on every call.

C: complete example.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
int cost(int price, int quantity) { return price * quantity; }
int main(void) {
    printf("%d\n", cost(6, 1));
    return 0;
}

Python: complete example.py

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

Watch the difference

A list default can retain mutations between calls. Use a default of None and create a list inside the function when each call needs fresh state. Supplying one parameter both positionally and by keyword raises TypeError.

Your code goes in functions.py. The locked driver.py is the entry file, supplies execution and checks, and cannot be edited.

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.

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.

Python defaults and named calls have no direct C call-syntax equivalent.

Your code goes in functions.py. The locked driver.py is the entry file, supplies execution and checks, and cannot be edited.

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