Menu
CoddyTech

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 collect

Python

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 icon

Challenge

Beginner

Implement 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))
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Python for Ruby Developers

Practice on your own: Online Python compiler