在Python中,函数是组织好的,可重复使用的,用来实现单一,或相关联功能的代码段。Python提供了许多内建函数,比如print()
,同时也允许创建自定义函数。
函数的定义
自定义函数使用def
关键字来定义。函数块以:
符号开始,后面跟着缩进的代码块。
def my_function():
print("Hello from a function")
调用函数
定义了函数之后,可以通过写函数名加上括号来调用它。
my_function()
参数
函数可以要求参数,所谓的参数就是调用函数时可以传递给函数的值。函数可以定义任意数量的参数。
def my_function_with_args(username, greeting):
print("Hello, %s , From My Function!, I wish you %s" % (username, greeting))
my_function_with_args("John Doe", "a great year!")
返回值
函数可以返回数据作为结果。在Python中,使用return
语句来返回值。
def sum_two_numbers(a, b):
return a + b
result = sum_two_numbers(10, 5)
print(result) # 输出:15
默认参数值
可以在函数定义中为参数提供默认值。调用函数时,如果没有传递参数,则会使用默认值。
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function() # 将输出默认值 Norway
my_function("Brazil")
关键字参数
函数调用时,可以使用参数名的形式来调用,这样不必担心参数的顺序。
def my_function(child3, child2, child1):
print("The youngest child is " + child3)
my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")
不定长参数
有时可能需要一个函数能处理比当初声明时更多的参数。这些参数称为不定长参数,和其他参数不同,声明时不会命名。
使用如下方法,可以在函数内部处理不定长参数:
*args
:接收多个参数并将其作为一个元组传递。**kwargs
:接收关键字参数字典。
def my_function(*args):
for arg in args:
print(arg)
my_function("Hello", "Welcome", "to", "GeeksforGeeks")
def my_function(**kwargs):
for key, value in kwargs.items():
print("%s == %s" % (key, value))
# 会输出每个传入的key=value形式的参数
my_function(first ='Geeks', mid ='for', last='Geeks')
匿名函数 Lambda
lambda
关键字可以创建小的匿名函数。Lambda函数可以接受任意数量的参数,但只能有一个表达式。
sum = lambda arg1, arg2: arg1 + arg2
print("Value of total : ", sum(10, 20)) # 输出:Value of total : 30
Lambda函数经常用于小的无需定义传统函数的操作,如排序列表时提供key
函数。
文档字符串
文档字符串(Docstring)提供了一种为函数添加文档的方式。在函数的第一行,使用三引号("""
)来定义字符串,可以使用__doc__
来访问文档。
def my_function():
"""Do nothing, but document it.
No, really, it doesn't do anything.
"""
pass
print(my_function.__doc__)
这些是Python中函数的基本和高级特性。Python的函数是学习Python编程的一个核心概念,它们提供了编写可维护代码的强大工具。