A function definition names a reusable block of Python code. It describes the inputs, operations, and returned value. The definition begins with def, followed by the function name, parenthesized parameters, and a colon. Indented lines form the function body. Defining a function does not run it; Python executes it only when another statement calls it. section 21.1 section 21.4
Read a function definition from the outside inward:
- The name identifies the task and follows the same naming rules as a variable. section 21.1
- Parameters describe the inputs; commas separate multiple parameters, while empty parentheses mean the function takes no inputs. section 21.1 section 22.1
- The indented body performs the work, and return sends a value back to the statement that called the function. section 21.1 section 21.4
- A triple-quoted docstring records expected inputs, behavior, and output so the implementation can be used without reading every line. section 22.1
Listing 21.1. A function to take class attendance
def take_attendance(classroom, who_is_here): #1
""" #2
classroom, tuple #2
who_is_here, tuple #2
Checks if every item in classroom is in who_is_here #2
And prints their name if so. #2
Returns "finished taking attendance" #2
""" #2
for kid in classroom: #3
if kid in who_is_here: #4
print(kid) #5
return "finished taking attendance" #6
Use the attendance function to trace the definition line, docstring, loop, condition, printed names, and returned message. section 21.1
A small reusable calculation
def get_word_length(word1, word2): word = word1 + word2 return len(word) The function combines two supplied strings and returns the length of the result. Code after return is not reached, so a later print statement inside the same function would never run. A caller can save or print the returned value. section 21.4





