A function is a callable program unit that packages an operation behind a name. It can accept arguments, return a result, and replace repeated code with a reusable, testable unit. section 7.14
Start with the smallest useful interface, then add flexibility only when the task requires it. A required parameter handles essential input; a default parameter handles optional input; *args accepts a variable number of positional values; and **kwargs collects keyword arguments in a dictionary. section 7.3
Functions become especially useful when they are treated as data:
- Pass a function as an argument, such as supplying a key function to sorted or a transformation function to map. section 4.10 section 8.5
- Store functions in a dictionary and retrieve one dynamically, as in a dispatch table for arithmetic operators. section 7.7
- Define and return an inner function to create related callable objects that retain a shared configuration. section 7.10
A configured function factory
create_password_generator('abcdef') returns a function that generates passwords from those characters. The returned function then accepts a length, so alpha_password(5) and alpha_password(10) use the same character set with different output sizes. section 7.10
def add(a,b):
return a + b
def sub(a,b):
return a - b
def mul(a,b):
return a * b
def div(a,b):
return a / b
def pow(a,b):
return a ** b
def mod(a,b):
return a % b
def calc(to_solve):
operations = {'+' : add, #1
'-' : sub,
'*' : mul,
'/' : div,
'**' : pow,
'%' : mod}
op, first_s, second_s = to_solve.split() #2
first = int(first_s) #3
second = int(second_s)
return operations[op](first, second) #4
A dispatch table maps operator strings to functions, splits and converts the input operands, then calls the selected function. section 7.7
Practice functions by solving focused transformations: alphabetize records, count distinct integers, report file statistics, or translate file contents. Check edge cases such as optional content, repeated values, whitespace, and unexpected input shape before generalizing the solution. section 4.10 section 5.16 section 6.10 section 8.14



















