函数
语法
def
:定义函数的关键字。function_name
:你给函数起的名字,遵循变量命名规则(通常是小写字母和下划线)。()
:括号,用于包含函数的参数。即使没有参数,括号也是必需的。parameters
:函数接收的输入值(变量名),多个参数用逗号,
分隔。这是可选的
python
def function_name(parameters):
"""函数文档字符串 (Docstring) - 可选,但强烈推荐"""
# 函数体 (执行的代码)
# ...
return value # 可选,用于返回值
案例
无参函数
python
# 无参
def greet():
print("你好,欢迎学习 Python 函数!")
# 调用 (执行) 函数
greet()
# 无参+返回值
def greet_with_return():
greeting = "你好,欢迎学习 Python 函数!"
return greeting
# 调用 (执行) 函数并打印返回值
print(greet_with_return())
有参
python
# 有参
def greet_with_name(name):
print("你好," + name + ",欢迎学习 Python 函数!")
# 调用 (执行) 函数并传入参数
greet_with_name("小明")
# 有参+返回值
def greet_with_name_and_return(name):
greeting = "你好," + name + ",欢迎学习 Python 函数!"
return greeting
# 调用
print(greet_with_name_and_return("小明"))
函数参数默认值
- 可以为函数定义中的参数指定默认值。如果在调用函数时没有为该参数提供实参,则使用默认值。
parameter_name=default_value
python
def power(base, exponent=2):
"""计算 base 的 exponent 次方,exponent 默认为 2。"""
return base ** exponent
# 调用函数,可以只提供必须的参数 base
square = power(4) # 没有提供 exponent,使用默认值 2
print(f"4 的平方是: {square}") # 输出: 4 的平方是: 16
# 调用函数,提供所有参数
cube = power(4, 3) # 提供了 exponent=3,覆盖默认值
print(f"4 的立方是: {cube}") # 输出: 4 的立方是: 64