Function Fundamentals
Defining Functions: Name, Body, and Invocation
A function encapsulates a block of code designed to perform a specific task. It executes only when called upon.
Syntax:
def function_name():
# function body (code block)
The function body contains the statements executed when the function is invoked. To execute a function, use its name followed by parentheses:
function_name() # Parentheses indicate function invocation
Naming Convantions:
- Use letters, numbers, and underscores
- Cannot start with a number (nor be purely numeric)
- Avoid Python keywords
- Keep names reasonably short
- Choose meaningful, descriptive names
- Avoid non-ASCII characters
- Prefer snake_case or CamelCase formatting
def display_message():
print('System initialized')
print('Ready to process requests')
display_message()
display_message()
Return Values
The return statement allows a function to send data back to the caller.
Key Behavior: When Python encounters return, the function terminates immediately. Any code after return does not execute.
def query_status():
print('Querying database connection')
print('Connection established')
print('Fetching records')
return # Function exits here
print('This line never runs')
query_status()
Multiple Return Values: Functions can return multiple values, which are packaged as a tuple.
def process_input():
print('Processing user input')
print('Validating data')
print('Applying transformations')
return 'completed', 42, ['item1', 'item2']
result = process_input()
print(result)
print(tuple(result))
print(list(result))
print(set(result))
Return Value Behavior:
- No
returnstatement or emptyreturn: returnsNone - Single value after
return: caller receives that value - Multiple values after
return: caller receives a tuple, wich can be unpacked into seperate variables
Function Parameters
Parameters enable functions to accept external data, making them flexible and reusable.
Syntax:
def function_name(parameter_list):
# function body
def open_app(app_name):
print('Unlocking device')
print('Launching: ' + app_name)
print('Loading interface')
print('Ready for interaction')
open_app('Twitter')
open_app('Instagram')
open_app('Telegram')
Terminology:
- Formal Parameter (形参): Variables defined in the function declaration. They represent placeholders for values the function expects.
- Actual Parameter (实参): Concrete values passed when calling the function.
- Passing Arguments: The process of transferring actual parameters to formal parameters.
def open_app(app_name): # app_name is a formal parameter
print('Unlocking device')
print('Launching: ' + app_name)
print('Loading interface')
print('Ready for interaction')
open_app('Twitter') # 'Twitter' is an actual parameter
len('Instagram') # 'Instagram' is an actual parameter
print('Telegram') # 'Telegram' is an actual parameter
Parameter Classification
Actual Parameter Types:
-
Positional Parameters: Arguments matched to parameters by their position.
-
Keyword Parameters: Arguments matched by explicitly naming the parameter.
-
Mixed Parameters: Combine both types. Positional parameters must come before keyword parameters.
def search_items(category, location, limit):
print('Searching ' + category)
print('Location: ' + location)
print('Maximum results: ' + str(limit))
print('Retrieving data')
search_items('Electronics', 'New York', 50) # Positional: matched by order
search_items(category='Books', location='Boston', limit=25) # Keyword: matched by name
Formal Parameter Types:
-
Positional Parameters: The standard approach used throughout this discussion.
-
Default Parameters: When many calls use the same value for a parameter, specify a default. Default parameters must follow positional parameters.
def search_items(category, location, limit=10):
print('Searching ' + category)
print('Location: ' + location)
print('Maximum results: ' + str(limit))
print('Retrieving data')
search_items('Furniture', 'Chicago') # limit uses default value (10)
search_items('Furniture', 'Chicago', 30) # limit uses provided value (30)
def find_maximum(x, y):
if x > y:
return x
else:
return y
def find_maximum(x, y):
result = x if x > y else y
return result
Positional vs. Keyword Parameters:
Positional parameters work well for functions with few arguments. However, when a function accepts numerous parameters, remembering both the parameter names and their order becomes burdensome. Keyword parameters solve this by allowing you to specify values by name, eliminating the need to memorize positions.
def search_items(category, location, limit):
print('Searching ' + category)
print('Location: ' + location)
print('Maximum results: ' + str(limit))
print('Retrieving data')
search_items(category='Clothing', location='Seattle', limit=15)
You can combine both approaches—providing some arguments positionally while using keyword syntax for others. Always place positional arguments before keyword arguments in the function call.