Appearance
Python 函数详解
在 Python 中,函数(Function)是一种组织代码的方式,它可以将代码块封装成可复用的模块,提高代码的可读性和复用性。
1. 定义函数
Python 使用 def
关键字定义函数。
示例:定义一个简单的函数
python
def greet(name):
return f"Hello, {name}!"
print(greet("Alice")) # 输出: Hello, Alice!
2. 参数类型
2.1 位置参数(Positional Arguments)
python
def add(a, b):
return a + b
print(add(3, 5)) # 输出: 8
2.2 关键字参数(Keyword Arguments)
python
def introduce(name, age):
print(f"我是{name},今年{age}岁。")
introduce(age=25, name="小明") # 关键字参数可以不按顺序
2.3 默认参数(Default Arguments)
python
def greet(name="Guest"):
print(f"Hello, {name}!")
greet() # 默认参数生效
2.4 可变参数(Variable-length Arguments)
*args(可变位置参数)
python
def sum_all(*numbers):
return sum(numbers)
print(sum_all(1, 2, 3, 4)) # 输出: 10
**kwargs(可变关键字参数)
python
def user_info(**info):
for key, value in info.items():
print(f"{key}: {value}")
user_info(name="小明", age=25, city="北京")
3. 函数返回值
3.1 返回单个值
python
def square(n):
return n ** 2
print(square(4)) # 输出: 16
3.2 返回多个值
python
def get_coordinates():
return (10, 20)
x, y = get_coordinates()
print(x, y) # 输出: 10 20
4. 变量作用域
4.1 局部变量(Local Variable)
python
def example():
x = 10 # 局部变量
print(x)
example()
# print(x) # 错误,x 在函数外不可访问
4.2 全局变量(Global Variable)
python
x = 100 # 全局变量
def example():
global x # 使用 global 关键字修改全局变量
x = 200
example()
print(x) # 输出: 200