def function_name(parameters): "函数文档字符串" function_suite return [expression]
# 可变参数示例 def add_nums(*nums): result = 0 for i in nums: result += i return result print(add_nums(1, 2, 3, 4)) #输出10 print(add_nums()) #输出0 # 关键字参数示例 def print_info(name, age): print("名字: ", name) print("年龄: ", age) return print_info(name="Tom", age=18) #输出名字: Tom, 年龄: 18
def outer(): print('outer function') def inner(): print('inner function') inner() return outer() #输出outer function 和 inner function
# lambda函数示例 # 对列表元素进行求和 result = functools.reduce(lambda x, y: x + y, [1, 2, 3, 4, 5]) print(result)
# 阶乘递归函数 def factorial(n): if n == 1: return 1 else: return n * factorial(n-1) print(factorial(5)) #输出120
# 函数的装饰器 def decorator_func(func): def wrapper_func(): print("Before function call") func() print("After function call") return wrapper_func @decorator_func def test_func(): print("Hello world") # 调用test_func函数 test_func() # 输出 Before function call Hello world After function call
标签: ddos