Understanding Python Functions: Definition, Syntax, and Usage
This article explains what Python functions are, how to define them with the def keyword, demonstrates calling functions, returning values, and covers various parameter types with clear code examples to help readers write clean and reusable code.
In Python programming, functions are the primary way to organize code into reusable blocks, enhancing readability, maintainability, and reusability.
1. What is a function?
A function is a predefined code block that performs a specific task, receiving inputs (parameters) and returning outputs (return values).
2. Defining a function
In Python, the def keyword is used. The basic syntax is:
def function_name(param1, param2, ...):
"""function docstring"""
# function body
return valueExplanation:
def : keyword to define a function.
Function name: identifier used to call the function, following Python naming rules.
Parameters: values passed to the function; optional.
Docstring: brief description enclosed in triple quotes; optional but recommended.
Function body: code block executed by the function.
return : statement that returns a result; optional, defaults to None .
Example:
def greet(name):
"""Print a greeting"""
print(f"Hello, {name}!")The function greet takes one parameter name and prints a greeting.
3. Calling a function
After defining, invoke a function by its name followed by parentheses, providing arguments if required.
Example:
greet("Alice") # Output: Hello, Alice!
greet("Bob") # Output: Hello, Bob!4. Function return values
Use the return statement to send back a value of any data type.
Example:
def add(a, b):
"""Return the sum of two numbers"""
return a + b
result = add(3, 5)
print(result) # Output: 85. Function parameters
Python supports several ways to pass arguments:
Positional parameters: values passed in order.
Keyword parameters: specify values by name, order optional.
Default parameters: provide default values, allowing omission.
Variable parameters: *args for arbitrary positional arguments, **kwargs for arbitrary keyword arguments.
Example:
def info(name, age=18, *args, **kwargs):
print(f"Name: {name}")
print(f"Age: {age}")
print(f"Other info: {args}")
print(f"More info: {kwargs}")
info("Alice", 20, "Beijing", "Student", hobby="reading", city="Shanghai")Summary
Functions are a crucial concept in Python; mastering their definition, invocation, parameters, and return values enables you to write clearer, more efficient, and maintainable code.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.