A Python function packages statements into a callable unit. Use one to give a task a name, pass it inputs, and use its result elsewhere. A call can also perform an action, such as print output. section 9.1 section 2.3.1
The core rules are:
- Define a function with def, a name, parentheses, and a colon. Indent its body. A docstring immediately after the definition describes its external behavior and parameters; comments can explain the implementation. section 9.1
- Call it with arguments by position or parameter name. Parameters can have defaults; * collects extra positional arguments into a tuple, and ** collects extra keyword arguments into a dictionary. Mixed calls need care: positional arguments come before named arguments. section 3.4.6 section 9.2.4
- return immediately ends the call and supplies a value of any type. If execution reaches no return, the result is None. A caller may assign a returned value or discard it. section 9.1 section 3.4.6
Define, call, and capture a result
def fact(n): """Return the factorial of the given number.""" result = 1 while n > 0: result *= n n -= 1 return result answer = fact(4) # answer is 24 The call runs the indented body; assigning its result keeps the value for later use. section 9.1
Functions are objects, not just names attached to definitions. Assign one to a variable, store functions in a dictionary, then call the selected value. This is useful when a string key determines which operation to run. Take care not to replace a function name with its returned string: the next attempted call will fail because that name no longer refers to a callable function. section 9.5 section 9.9.2
t = {'FtoK': f_to_kelvin, 'CtoK': c_to_kelvin} #1
t['FtoK'](32) #2
273.15
t['CtoK'](0) #3
273.15
#1 Creates dictionary with both functions as values
#2 Accesses the f_to_kelvin function as value in dictionary
#3 Accesses the c_to_kelvin function as value in dictionary
Two temperature-conversion functions are dictionary values; selecting a key selects the function to call. section 9.5
Functions also work as callbacks. With a compiled regular expression, sub can receive a replacement function instead of a fixed string. It passes each match object to that function and uses the returned string for that match. A function can therefore make each replacement depend on what was found. section 16.5.1
For larger programs, move distinct tasks into functions and have the calling code use their returned values. A controlling main function can coordinate them; reusable functions can later live in a module. Prefer functions that do one thing and avoid effects that carry beyond the call. A dictionary cache is a deliberate alternative when repeated calls with identical arguments would otherwise repeat costly work. section 9.9 section 11.3 section 7.6



















