Python---函数的几种参数

  1. 位置参数
  2. 关键字参数   (键=值)
  3. 缺省参数       (默认值必须写在最后)
  4. 不定长参数   (1:位置传递 ,2:关键字传递)
  5. 函数作为参数传递  (计算逻辑的传递,而非数据的传递)

例子:

# 参数传递参数
def user_info(name, age, gender):
    print(f"姓名:{name},年龄:{age},性别:{gender}")


# 位置参数
user_info("小米", 18, "男")

# 关键字参数  ----- 键=值
user_info(name="小米", age=18, gender="男")
user_info(age=18, gender="男", name="小米")
user_info("小米", age=18, gender="男")


# 缺省参数  ------- 必须在最后
def user_info1(name1, age1, gender1="男"):
    print(f"姓名:{name1},年龄:{age1},性别:{gender1}")


user_info1(name1="小米", age1=18)
user_info1(name1="小米", age1=18, gender1="女")


# 不定长参数   ------ 类型1:位置传递  类型2:关键字传递
# 位置传递不定长  ---- 元组的形式
def user_info2(*args):  # 元组
    print(args, type(args))


user_info2(1, 2, "你好", "hello")


# 关键字传递不定长  ---- 字典的形式
def user_info3(**kwargs):  # 字典
    print(kwargs, type(kwargs))


user_info3(a=1, b=2, c="你好", d="hello")


# 函数作为参数传递 ----- 计算逻辑的传递,而非数据的传递
def user_info4(compute):
    result = compute(1, 2)
    print(result,type(compute))   # 3 <class 'function'>

def compute(x, y):
    return x + y

user_info4(compute)
如果一个函数要返回多个返回值该如何书写?
按照返回值的顺序,写对应顺序的多个变量接收即可,变量之间用逗号隔开,支持不同类型的数据return
def r_test():
    return 1, 2, 3


x, y, z = r_test()
print(x)
print(y)
print(z)

猜你喜欢

转载自blog.csdn.net/weixin_52053631/article/details/132866878