Defaults Run at Definition
Lesson 23 of 48 in Coddy's Python for Ruby Developers course.
Ruby default argument expressions run when a call needs that default. Python evaluates a default expression when its def statement executes. A mutable Python default therefore persists across calls. Use None as a sentinel and construct a fresh list inside the function when each call needs independent state. Python parameters can usually be supplied positionally or by keyword using name=value; Ruby distinguishes keyword parameters declared with a colon from ordinary positional parameters. Python rejects providing the same argument both positionally and by name. Defaults fill missing values; they do not permit duplicate bindings or arbitrary unknown keyword names.
Ruby
def collect(items = [])
items << 1
items.length
end
puts collect
puts collectPython
def collect(items=[]):
items.append(1)
return len(items)
print(collect())
print(collect())Porting trap
A Ruby default empty array does not translate safely to a Python default empty list when the function mutates it. Prefer the sentinel pattern.
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 Ruby Developers
1From Ruby to Python
Run Your First Python ProgramStrings and InterpolationNames and Mutable StringsDivision and ParsingFrom end to IndentationRecap: Rewrite a Receipt4Iteration and Transformations
each and Python foreach_pair and enumeratenext Becomes continueselect, map, and sort_byRecap: Build a Ranking2Values and Decisions
nil Becomes None== and equal?Zero Is False in Pythonelsif and Conditional ValuesRecap: Eligibility Rules5Functions and Closures
Explicit Return ValuesDefaults Run at DefinitionSplat and Double SplatBlocks Become CallablesRecap: Refactor a Pricing Tool3Collections and References
Array Methods and ListsParallel Assignment and TuplesHash Defaults and Dict Keysdup, Copies, and SetsRecap: Clean an Inventory6Reliable Python Programs
gets, input, and Formattingrescue and Context Managersrequire and Import GuardsHints Do Not Enforce TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler