Python函数
封面图
•
2025-12-05
•
Python
230
0
0
0
当然!Python 函数是用于封装可重复使用的代码块。你可以定义函数来执行特定任务,然后在程序中多次调用它。 ### 1. **定义函数的基本语法** ```python def function_name(parameters): # 函数体 return [expression] ``` ### 2. **示例:一个简单的函数** ```python def greet(name): print(f"Hello, {name}!") greet("Alice") # 输出: Hello, Alice! ``` ### 3. **带返回值的函数** ```python def add(a, b): return a + b result = add(3, 5) print(result) # 输出: 8 ``` ### 4. **默认参数** ```python def greet(name, message="Welcome!"): print(f"{message}, {name}!") greet("Bob") # 输出: Welcome!, Bob greet("Alice", "Hi") # 输出: Hi, Alice ``` ### 5. **关键字参数** ```python def describe_person(name, age, city): print(f"{name} is {age} years old and lives in {city}.") describe_person(age=30, name="John", city="New York") ``` ### 6. **可变参数(*args 和 **kwargs)** - `*args`:接收任意数量的非关键字参数 - `**kwargs`:接收任意数量的关键字参数 ```python def print_args(*args, **kwargs): print("Positional arguments:", args) print("Keyword arguments:", kwargs) print_args(1, 2, 3, name="Alice", age=25) # 输出: # Positional arguments: (1, 2, 3) # Keyword arguments: {'name': 'Alice', 'age': 25} ``` ### 7. **匿名函数(lambda)** ```python square = lambda x: x ** 2 print(square(5)) # 输出: 25 ``` --- 如果你有具体的使用场景或想了解某个函数特性(如递归、装饰器等),可以告诉我,我可以详细讲解 😊
上一篇:
apach ssl.conf 介绍
下一篇:
什么是Apache web服务器?
标题录入,一次不能超过6条
留言
评论