本文共 909 字,大约阅读时间需要 3 分钟。
在 Python 中,函数的参数是在小括号中定义和传递的。函数接受多种数据类型的参数,可以是数字、字符串、列表、字典等。
def foo(x, y): print("x 的值是:", x) print("y 的值是:", y) foo(2, 3) # 调用函数,传递参数 x=2,y=3
在定义参数时,可以为某些参数设定默认值。默认参数在调用函数时可以省略,使用时会取默认值。
def conn_mysql(user, port=3306): print(user, port)
conn_mysql("root") # 未传递 port,使用默认值 3306conn_mysql("root", 3307) # 传递了 port,使用 3307 注意:所有默认参数必须排在所有位置参数之后。
user。port。conn_mysql("root", 3307)。conn_mysql(port=3308, user="sahrk")
函数处理的数据只有通过 return 关键字才能返回给调用者。
def foo(): n = 3 + 7 return n
n = foo() # n 的值为 10
def func(): return 1, "hello", [1, 2], {"a": 1} t = func() # 返回值为 (1, 'hello', [1, 2], {'a': 1}) n, s, li, dic = func() # 解包获取各个返回值print(n, s, li, dic) # 输出 1 hello [1, 2] {'a': 1} 函数可以返回任意数量的任意 Python 数据对象。例如,可以返回数字、字符串、列表、字典等多种类型的数据。
转载地址:http://dhjg.baihongyu.com/