Python的函数定义使用def关键字,与C++等语言不同,Python不使用大括号来标记函数体,而是依靠缩进来区分代码块。本文将详细介绍Python函数定义的方式和特点。
一、Python函数定义的基本语法 1. 基本结构 1 2 3 4 5 6 def greet (): print ("Hello, World!" ) greet()
2. 带参数的函数 1 2 3 4 5 6 7 8 9 10 11 12 def greet (name ): print (f"Hello, {name} !" ) greet("Alice" ) def add (a, b ): return a + b result = add(3 , 5 ) print (result)
3. 默认参数值 1 2 3 4 5 6 7 8 9 def greet (name, greeting="Hello" ): print (f"{greeting} , {name} !" ) greet("Alice" ) greet("Bob" , "Hi" )
4. 关键字参数 1 2 3 4 5 6 def introduce (name, age, city ): print (f"I am {name} , {age} years old, from {city} " ) introduce(age=25 , name="Alice" , city="Beijing" )
二、Python与C++函数定义的对比 1. 语法对比 C++ :
1 2 3 4 5 6 7 8 9 int add (int a, int b) { return a + b; } auto add = [](int a, int b) { return a + b; };
Python :
1 2 3 def add (a, b ): return a + b
2. 缩进vs大括号 C++ :
1 2 3 4 5 6 7 void func () { if (condition) { do_something (); } else { do_other (); } }
Python :
1 2 3 4 5 def func (): if condition: do_something() else : do_other()
3. 返回值 C++ :
1 2 3 4 5 6 7 8 9 int get_value () { return 42 ; } void print_message () { cout << "Hello" << endl; }
Python :
1 2 3 4 5 6 7 8 9 def get_value (): return 42 def print_message (): print ("Hello" ) print (print_message())
三、缩进规则 1. 缩进的重要性 1 2 3 4 5 6 7 8 9 10 def correct_indent (): print ("This is inside the function" ) if True : print ("This is inside the if block" ) print ("Back to the function level" )
2. 缩进的一致性 1 2 3 4 5 6 7 def four_spaces (): print ("Four spaces is standard" ) def tab_indent (): print ("Tab indentation" )
3. 多层缩进 1 2 3 4 5 6 7 8 9 10 11 12 def outer_function (): print ("Outer function" ) def inner_function (): print ("Inner function" ) def deeply_nested (): print ("Deeply nested" ) deeply_nested() inner_function()
四、特殊函数参数 1. *args(可变位置参数) 1 2 3 4 5 6 7 8 def sum_all (*args ): total = 0 for num in args: total += num return total print (sum_all(1 , 2 , 3 )) print (sum_all(1 , 2 , 3 , 4 , 5 ))
2. **kwargs(可变关键字参数) 1 2 3 4 5 6 7 8 9 def print_info (**kwargs ): for key, value in kwargs.items(): print (f"{key} : {value} " ) print_info(name="Alice" , age=25 , city="Beijing" )
3. 参数组合 1 2 3 4 5 6 7 8 9 10 def func (required, *args, **kwargs ): print (f"Required: {required} " ) print (f"Args: {args} " ) print (f"Kwargs: {kwargs} " ) func(1 , 2 , 3 , name="Alice" , age=25 )
五、函数文档和注解 1. Docstring(文档字符串) 1 2 3 4 5 6 7 8 9 10 11 12 13 def calculate_area (radius ): """Calculate the area of a circle. Args: radius: The radius of the circle. Returns: The area of the circle. """ import math return math.pi * radius ** 2 print (calculate_area.__doc__)
2. 类型注解 1 2 3 4 5 6 7 8 9 10 11 12 def greet (name: str ) -> str : return f"Hello, {name} " def add (a: int , b: int ) -> int : return a + b from typing import List , Union def process (items: List [Union [int , str ]] ) -> List [str ]: return [str (item) for item in items]
六、综合示例 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 """ Python函数定义综合示例 """ def basic_operations (a, b ): """基本数学运算""" return { 'sum' : a + b, 'difference' : a - b, 'product' : a * b, 'quotient' : a / b if b != 0 else None } def with_defaults (name, greeting="Hello" , punctuation="!" ): """带默认参数的函数""" return f"{greeting} , {name} {punctuation} " def variable_args (*args, operation="sum" ): """可变参数函数""" if operation == "sum" : return sum (args) elif operation == "product" : result = 1 for num in args: result *= num return result else : return None def keyword_args (**kwargs ): """关键字参数函数""" return "\n" .join(f"{key} : {value} " for key, value in kwargs.items()) def demo (): """演示函数""" print ("=== 基本运算 ===" ) result = basic_operations(10 , 5 ) for op, value in result.items(): print (f"{op} : {value} " ) print ("\n=== 默认参数 ===" ) print (with_defaults("Alice" )) print (with_defaults("Bob" , "Hi" )) print (with_defaults("Charlie" , "Hey" , "^^^" )) print ("\n=== 可变参数 ===" ) print (f"Sum: {variable_args(1 , 2 , 3 , 4 , 5 )} " ) print (f"Product: {variable_args(1 , 2 , 3 , 4 , 5 , operation='product' )} " ) print ("\n=== 关键字参数 ===" ) print (keyword_args(name="Alice" , age=25 , city="Beijing" )) if __name__ == "__main__" : demo()
七、注意事项 1. 不要混用缩进风格 1 2 3 4 def mixed_indent (): print ("Space" ) print ("Tab" )
2. 默认参数不要使用可变对象 1 2 3 4 5 6 7 8 9 10 11 def wrong_func (items=[] ): items.append(1 ) return items def correct_func (items=None ): if items is None : items = [] items.append(1 ) return items
3. 函数调用必须在定义之后 1 2 3 4 5 greet() def greet (): print ("Hello!" )