Positional and Keyword Args
Lesson 23 of 48 in Coddy's Python for JavaScript Developers course.
Design functions with clear defaults and let callers name optional arguments without sharing accidental mutable state.
JavaScript
function repeat(text, count = 2) {
return text.repeat(count);
}
console.log(repeat("ha", 3));Python
def repeat(text, count=2):
return text * count
print(repeat(count=3, text="ha"))What changes
Both programs print hahaha. Python binds positional arguments from left to right. Keyword arguments bind by parameter name, so their order can differ from the definition. In ordinary calls, place positional arguments before keyword arguments and never supply the same parameter twice. JavaScript has no corresponding native named-parameter call syntax; an options object is a common design instead. Python defaults are evaluated when the function definition runs, not on every call. A default list therefore survives across calls. JavaScript evaluates a default initializer at call time when the corresponding argument is omitted or undefined. Python uses a default when the argument is omitted; explicitly passing None supplies a real value.
Common mistake
For a fresh optional list, use None as the default and create a list inside the function after an is None check. Do not use general truthiness for this check: a caller may intentionally pass an empty list that should be mutated.
Your task
Practice positional and keyword calls, then repair the shared-default problem in a mastery exercise with repeated calls.
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 JavaScript Developers
1From JavaScript to Python
Run Your First Python ProgramPrint, Comments, and StringsVariables Without let or constNumbers and ConversionBlocks Use IndentationRecap: Rewrite a Receipt4Iteration and Transformations
for Loops Iterate ValuesIndexes and Dict Iterationwhile, break, and continueComprehensions and SortingRecap: Build a Ranking2Values and Decisions
None, True, and FalseEquality and IdentityTruthiness and Short-CircuitBranches and ExpressionsRecap: Eligibility Rules5Functions and Scope
Define and ReturnPositional and Keyword ArgsExtra Arguments and UnpackingScope, Callbacks, and LambdasRecap: Refactor a Pricing Tool3Collections and References
Lists Instead of ArraysTuples and UnpackingDictionaries and RecordsSets, Aliasing, and CopiesRecap: Clean an Inventory6Reliable Python Programs
Input and Output ContractsExceptions and ValidationModules and the Main GuardReading Type HintsRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler