函数基础
在编程中,函数是组织好的、可重复使用的、用于实现单一或相关联功能的代码块。它们提高了代码的可读性、可维护性和复用性。以下是对函数基础及其相关概念的详细解释和代码示例。
1. 函数目的
函数的目的是将一组特定的操作封装起来,以便在需要时重复调用,实现代码的复用。
2. 函数定义
函数通过def
关键字来定义。它后面跟着函数名和圆括号(可能包含参数),然后是冒号和函数体。
def greet(name):
print(f"Hello, {name}!")
3. 函数声明
在Python中,定义函数的同时也声明了它。上面greet
函数的定义就是一个声明。
4. 函数调用
通过函数名加圆括号(可能包含实参)来调用函数。
greet("Alice") # 输出: Hello, Alice!
5. 函数形参
函数定义时圆括号内的参数称为形式参数(简称形参),它们是函数期望接收的值的占位符。
def add(a, b):
return a + b
6. 函数实参
调用函数时传递给函数的值称为实际参数(简称实参)。
result = add(3, 4) # 3和4是实参
print(result) # 输出: 7
7. 函数返回值
函数可以通过return
语句返回一个值给调用者。
def square(x):
return x * x
result = square(5)
print(result) # 输出: 25
8. 函数的参数类型
Python是动态类型语言,函数参数不需要声明类型,但在实际使用中,应该遵循约定俗成的类型规范。
def greet_person(name: str):
print(f"Hello, {name}!") # 类型注解,不强制类型检查
9. 变量的作用域(global与nonlocal)
global
:用于在函数内部声明全局变量。nonlocal
:用于在嵌套函数中声明非局部变量,即外层函数的局部变量。x = 10 def outer(): x = 5 def inner(): nonlocal x x = 20 print(f"Inner: {x}") inner() print(f"Outer: {x}") outer() # 输出: # Inner: 20 # Outer: 20
10. 递归函数
函数直接或间接地调用自身称为递归。
def factorial(n): if n == 1: return 1 else: return n * factorial(n-1) print(factorial(5)) # 输出: 120
11. 匿名函数
使用
lambda
关键字创建匿名函数。square = lambda x: x * x print(square(5)) # 输出: 25
12. 闭包
闭包是一个函数值,它引用了其外部作用域的变量。
def outer(text): def inner(): return text return inner func = outer("Hello") print(func()) # 输出: Hello
13. 装饰器
装饰器是修改其他函数或类的功能的函数。
def my_decorator(func): def wrapper(): print("Something is happening before the function is called.") func() print("Something is happening after the function is called.") return wrapper @my_decorator def say_hello(): print("Hello!") say_hello() # 输出: # Something is happening before the function is called. # Hello! # Something is happening after the function is called.