Python函数和模块——详细介绍
Python函数介绍
在Python中,函数是组织好的,可重复使用的,用来实现单一或关联功能的代码段,Python提供了许多内置函数,比如print()
,也允许创建用户自定义的函数。
创建函数
你可以使用def
关键字来定义一个函数。以下是函数的一般形式:
def function_name(parameters):
"""docstring"""
statement(s)
function_name
:函数的名称。parameters
:函数可以接受的输入参数,它们是可选的。docstring
:函数的文档字符串,用来描述函数的作用,这也是可选的。statement(s)
:函数内部的代码块。
例子
def greet(name):
"""This function greets to the person passed in as parameter"""
print("Hello, " + name + " Good morning!")
调用函数
调用函数时,只需将参数值传递给函数。如果函数接受参数,那么在调用函数时提供相同数量的参数是必要的。
# 调用上面的函数
greet('John')
返回值
使用return
语句,函数可以返回值。
def add(a, b):
"""This function returns the sum of two numbers"""
return a + b
# 调用函数并打印结果
result = add(3, 4)
print(result) # 输出: 7
默认参数和关键字参数
函数参数可以有默认值。如果调用时没有提供值,将使用参数的默认值。
def greet(name, msg="Good morning!"):
print("Hello", name + ', ' + msg)
greet("Kate") # 输出: Hello Kate, Good morning!
greet("Bruce", "How do you do?") # 输出: Hello Bruce, How do you do?