在Python中,函數(shù)定義主要有以下幾種類型:
def
關(guān)鍵字定義的函數(shù),需要為函數(shù)指定一個(gè)名稱。例如:def my_function():
print("This is a normal function.")
lambda
關(guān)鍵字定義的匿名函數(shù),通常用于簡(jiǎn)單的操作,不需要指定函數(shù)名。例如:my_lambda = lambda x: x * 2
print(my_lambda(5)) # 輸出:10
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
def apply(func, x):
return func(x)
def square(x):
return x * x
result = apply(square, 5) # 輸出:25
yield
關(guān)鍵字定義的函數(shù),用于生成一個(gè)迭代器。例如:def fibonacci(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
fib = fibonacci(5)
for num in fib:
print(num) # 輸出:0 1 1 2 3