Introduction to Python Functions

Introduction to Python Functions

1. What is a Function?

1.1 Core Concepts of Functions

A function is a block of reusable code with the following core characteristics:

  • Function Encapsulation: Wraps specific task code into an independent unit
  • Input and Output: Accepts input (parameters) and returns results (return values)
  • Namespace: Internal variables are isolated from external ones
  • Code Reusability: Avoids rewriting the same logic

1.2 Real-World Analogy

Programming Concept Real-World Analogy Description
Function Definition Recipe Instructions for making a dish
Function Call Cooking according to the recipe Executing the operation process
Parameters Ingredients Raw materials needed for preparation
Return Value Finished Dish Result of the operation
Variable Scope Kitchen Area Internal tools are not borrowed externally

2. Basic Syntax for Function Definition

2.1 Standard Definition Format

def function_name(parameter1, parameter2, ...):
    """Documentation string (optional)"""
    function_body_code
    return return_value

2.2 Key Components

  1. def Keyword: Indicates the start of a function
  2. Function Name: Follows variable naming rules (lowercase + underscore)
  3. Parameter List: Declares input parameters within parentheses
  4. Colon : Marks the end of the function header
  5. Indented Code Block: Function body indented by 4 spaces
  6. return Statement: Returns results (optional)
# Example: Calculate Rectangle Area
def calc_area(width, height):
    """Calculate rectangle area"""
    area = width * height
    return area

3. Core Principles of Function Naming

3.1 PEP 8 Naming Conventions

The official Python style guide (PEP 8) defines function naming rules:

  • All Lowercase Letters: Use all lowercase characters
  • Underscore Separation: Connect words with underscores
  • Verb Priority: Use verbs or verb phrases for naming
  • Concise and Clear: Accurately describe the function’s purpose
# Correct Examples
def calculate_total_price():
def format_user_name():
def save_to_database():

# Incorrect Examples
def CalculateTotal():  # Used uppercase
def formatUserName():  # Used camel case
def saver():           # Too vague

3.2 Categorization by Functionality

Function Type Naming Pattern Example Description
Action Type <span>verb_object()</span> <span>calculate_tax()</span> Performs a specific action
Condition Type <span>is_condition()</span> <span>is_valid_email()</span> Returns a boolean value
Getter Type <span>get_attribute()</span> <span>get_user_age()</span> Retrieves attribute values
Converter Type <span>to_format()</span> <span>to_json()</span> Data format conversion
Checker Type <span>has_feature()</span> <span>has_duplicates()</span> Checks for the existence of features

3.3 Categorization by Scope

Function Type Naming Pattern Example Description
Public Function <span>regular_name()</span> <span>process_data()</span> Module-level public function
Private Function <span>_internal_use()</span> <span>_validate_input()</span> For internal use only (not strictly private)
Special Method <span>__special__()</span> <span>__init__()</span> Python internal protocol methods

3.4 Naming Length Guidelines

Naming Length Recommendation Example
Too Short (<6 characters) Avoid <span>cal()</span>, <span>fmt()</span>
Moderate (8-15 characters) Recommended <span>calculate_total()</span>, <span>format_date()</span>
Too Long (>20 characters) Refactor <span>calculate_monthly_revenue_before_tax()</span> to multiple functions or parameterize

3.5 Abbreviation Usage Rules

# Avoid uncommon abbreviations
def calc_usr_prof():    # Poor: usr=user, prof=profile
def get_user_profile()   # Good

# Common abbreviations allowed
def sync_db():          # db=database (common)
def config_ui():        # ui=user interface (common)

4. Function Calling Methods

4.1 Basic Calling Method

# Define function
def greet(name):
    return f"Hello, {name}!"

# Call function
message = greet("Zhang San")
print(message)  # Output: Hello, Zhang San!

4.2 Call Process Analysis

Introduction to Python Functions

5. Parameter Passing Mechanism

5.1 Basic Parameter Types

Parameter Type Syntax Characteristics Example
Required Parameter <span>def func(a, b)</span> Must be provided during the call <span>func(10, 20)</span>
Default Parameter (during function definition) <span>def func(a=5)</span> Can be omitted during the call <span>func()</span><span> → </span><code><span>a=5</span>
Keyword Parameter (during function call) <span>func(a=10, b=20)</span> Passed by parameter name <span>func(b=30, a=15)</span>
Variable Parameter <span>def func(*args)</span> Accepts any number of positional parameters <span>func(1,2,3)</span>
Keyword Variable Parameter <span>def func(**kwargs)</span> Accepts any number of keyword parameters <span>func(x=10, y=20)</span>

5.2 Parameter Combination Example

def build_profile(name, age, *hobbies, **details):
    """Create user profile"""
    print(f"Name: {name}")
    print(f"Age: {age}")
    print("Hobbies:", hobbies)  # Tuple format
    print("Details:", details)  # Dictionary format

# Call
build_profile("Li Si", 25, "Photography", "Travel", city="Beijing", occupation="Engineer")
"""
Output:
Name: Li Si
Age: 25
Hobbies: ('Photography', 'Travel')
Details: {'city': 'Beijing', 'occupation': 'Engineer'}
"""

6. Handling Return Values

6.1 Characteristics of the return Statement

  1. The function ends immediately upon reaching return
  2. Can return any type of data
  3. Can return multiple values (actually a tuple)
  4. If no return statement, defaults to None
# Return a single value
def get_square(n):
    return n * n

# Return multiple values
def calc_circle(radius):
    area = 3.14 * radius ** 2
    circumference = 2 * 3.14 * radius
    return area, circumference  # Actually returns a tuple

# Function with no return value
def show_info(msg):
    print("Prompt message:", msg)
    # Implicitly returns None

6.2 Handling Multiple Return Values

# Receive returned tuple
result = calc_circle(5)
print("Area and Circumference:", result)  # (78.5, 31.4)

# Unpack return values
area, circ = calc_circle(3)
print(f"Area: {area}, Circumference: {circ}")

# Ignore some return values
area, _ = calc_circle(4)  # Ignore circumference
print("Area:", area)

7. Documentation Strings and Comments

7.1 Documentation String Standards

def format_name(first, last):
    """Format user name
    
    Parameters:
        first (str): First name
        last (str): Last name
    
    Returns:
        str: Formatted full name "Last name, First name"
        
    Example:
        >>> format_name("Xiao Ming", "Zhang")
        'Zhang, Xiao Ming'
    """
    return f"{last}, {first}"

# View documentation
help(format_name)
print(format_name.__doc__)

7.2 Documentation Tool Generation Effect

Help on function format_name in module __main__:

format_name(first, last)
    Format user name
    
    Parameters:
        first (str): First name
        last (str): Last name
    
    Returns:
        str: Formatted full name "Last name, First name"
        
    Example:
        >>> format_name("Xiao Ming", "Zhang")
        'Zhang, Xiao Ming'

8. Practical Applications of Functions

8.1 Temperature Converter

def celsius_to_fahrenheit(celsius):
    """Convert Celsius to Fahrenheit"""
    return celsius * 9/5 + 32

def fahrenheit_to_celsius(fahrenheit):
    """Convert Fahrenheit to Celsius"""
    return (fahrenheit - 32) * 5/9

# Usage
temp_c = 37
temp_f = celsius_to_fahrenheit(temp_c)
print(f"{temp_c}℃ = {temp_f:.1f}℉")  # 37℃ = 98.6℉

temp_f = 100
temp_c = fahrenheit_to_celsius(temp_f)
print(f"{temp_f}℉ = {temp_c:.1f}℃")  # 100℉ = 37.8℃

8.2 Simple Calculator

def calculate(operation, a, b):
    """Perform basic arithmetic operations"""
    match operation:
        case '+':
            return a + b
        case '-':
            return a - b
        case '*':
            return a * b
        case '/':
            if b == 0:
                return "Error: Division by zero"
            return a / b
        case _:
            return "Error: Invalid operator"

# Usage
print("10 + 5 =", calculate('+', 10, 5))
print("20 / 4 =", calculate('/', 20, 4))
print("7 * 0 =", calculate('*', 7, 0))

9. Common Error Solutions

Error Type Cause Solution
<span>NameError: name 'func' is not defined</span> Function called before definition Ensure function is defined before calling
<span>TypeError: func() missing 1 required positional argument</span> Missing required parameter Check function parameter definitions
<span>SyntaxError: expected ':'</span> Missing colon in function header Add colon at the end of def statement
<span>IndentationError: expected an indented block</span> Missing indentation in function body Consistently indent function body by 4 spaces
<span>UnboundLocalError</span> Using local variable before assignment Declare global variable using global statement

Conclusion: Full Process of Function Usage

Introduction to Python Functions

Python functions are the building blocks of programming. Master the core points:

  1. Definition: Use <span>def</span> keyword + function name + parameter list
  2. Call: Pass actual parameters through function name()
  3. Parameters: Supports various forms such as required, default, variable, etc.
  4. Return Values: Use return to return results, can return multiple values
  5. Scope: Understand the scope of local and global variables

By designing and using functions effectively, you can build modular, reusable, and maintainable code structures, which are the foundation of all excellent Python programs.

Follow me for more Python learning resources, practical projects, and industry updates! Reply “python learning” in the public account backend to get Python learning e-books!

Leave a Comment