Python — Functions, scope, and divmod
A Python function can return values for another calculation. divmod returns the quotient and remainder together, which the caller can unpack into two names.
A simple example
Call a function with 2
- Start with Argument 2
- Do this Double the argument
- Result 4
def twice(n):
return n + n
print(twice(2))
4
Calculate how many boxes an order needs
divmod returns the quotient and remainder in one call. Tuple unpacking names both results. The return expression produces a value that another function or test can reuse.
A library ships 17 books in cartons that hold eight. Two cartons take sixteen books, leaving one book that still needs a carton. An order of exactly sixteen needs only two.
Run the example
Python 3.8 or later. Run these commands from the directory containing the example.
python3 lesson.py
def boxes_needed(items, capacity):
full, remainder = divmod(items, capacity)
return full + (1 if remainder else 0)
print(boxes_needed(17, 8))
print(boxes_needed(16, 8))
3 2
The input contract is a nonnegative whole-number item count and a positive box capacity. Seventeen items fill two boxes of eight with one item left over. Sixteen items fill exactly two boxes.
Try it yourself
How many boxes do zero items need?
Check your answer
Zero. The quotient and remainder are both zero. A zero capacity is outside the function’s contract because division by zero is undefined.