Defaults and Named Arguments
Lesson 23 of 48 in Coddy's Python for C++ Developers course.
Python calls may bind arguments by position or parameter name. cost(quantity=3, price=4) binds by names rather than order; C++ has no equivalent ordinary named-argument call syntax. Defaults fill omitted parameters. Python evaluates a default expression when def executes, whereas C++ default argument expressions are evaluated at the call using them. A mutable Python default list is therefore reused between calls. Prefer None as the default and construct a fresh list inside when each call needs its own state.
C++17 excerpt: inside main
Standard-library headers are supplied in the runnable companion program.
auto cost = [](int price, int quantity = 1) { return price * quantity; };
std::cout << cost(4) << '\n' << cost(4, 3) << '\n';Python
def cost(price, quantity=1):
return price * quantity
print(cost(4))
print(cost(quantity=3, price=4))Porting trap
Passing a value both positionally and by keyword raises TypeError. Keyword arguments do not overwrite an earlier binding.
Implement the task below in its editable Python modules. The locked driver.py supplies execution and checks. Keep the specified imports and API names.
Challenge
BeginnerImplement line_cost(price, quantity=1, discount=0). Return price * quantity - discount as an integer. Inputs are nonnegative integers and the discount never exceeds the product. Do not print or read input. The locked driver reads price, quantity, and discount on three lines. It calls your function with just price, with two positional arguments, and with all arguments named in a different order. It prints the three results on separate lines.
Your function definitions go in functions.py. The locked driver.py imports them and handles the supplied input/output and checks. You do not need to edit the driver.
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))
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Python for C++ Developers
1From C++ to Python
Run Your First Python ProgramStreams to printNames, auto, and constDivision and Integer RangeBlocks and Name ScopeRecap: Rewrite a Receipt4Iteration and Transformations
Range Loops and RebindingEntries and enumerateLoop Control Without ++Algorithms and ComprehensionsRecap: Build a Ranking2Values and Decisions
None, nullptr, and boolValues, Addresses, IdentityTruth Tests and OperandsBranches and Value SelectionRecap: Eligibility Rules5Functions, Calls, and Closures
Functions and Shared ObjectsDefaults and Named ArgumentsPacking and Unpacking CallsClosures and Capture TimingRecap: Refactor a Pricing Tool3STL Habits and Python Objects
From vector to listTuples and Structured BindingsMaps, Keys, and OrderingValue Copies and Shared ListsRecap: Clean an Inventory6Errors, Resources, and Modules
Text Input and Exact OutputExceptions and RAIIModules Instead of HeadersHints Are Not Static TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler