Python--function (parameter and value transfer of function)

1. Function parameter and value transfer

1.1 Function parameters and actual parameters

Insert picture description here


1.2 Passing actual parameters

鉴于函数定义中可能包含多个形参,因此函数调用中也可能包含多个实参。
向函数传递实参的方式很多,可使用位置实参,
这要求实参的顺序与形参的顺序相同;也可使用关键关传参 ,
其中每个实参都由变量名和值组成;
还可使用列表和字典。下面来依次介绍这些方式。

1.2.1 Position parameters

最简单的关联方式是基于实参的顺序。这种关联方式被称为位置实参
  • The quantity must be consistent with the definition.
  • The location must be consistent with the definition.

Example:

def describe_pet(animal_type, pet_name):
    """显示宠物的信息"""
    print("\nI have a " + animal_type + ".")
    print("My " + animal_type + "'s name is " + pet_name.title() + ".")


describe_pet("dog", "wangwang")

operation result:
Insert picture description here


1.2.2 Keyword parameter transfer

关键字实参,是传递给函数的名称—值对.

Example:

describe_pet(animal_type="dog", pet_name="wangwang")

1.2.3 Default parameters

定义函数时可以指定形式参数的默认值。调用函数时,可分为以下两种情况:

Insert picture description here

Example:

def print_info(name="周天天", age=20):
    """打印信息"""
    print("姓名 :" + name + ", 年龄 : " + str(age))


print_info()

operation result:Insert picture description here


1.2.4 Variable parameters

不定长参数也叫可变参数。
用于不确定调用的时候会传递多少个参数(不传参也可以)的场景。

Insert picture description here
Insert picture description here
Example: Define a function so that it can receive any number of actual parameters

def print_schools(*name):
    print("\n我梦想的大学: ")
    for item in name:
        print(item)


print_schools("清华大学", "北京大学", "重庆大学", "西南大学", "武汉大学", "国防科技大学")

operation result:
Insert picture description here


Insert picture description here
Example: Define a function so that it can receive multiple actual parameters for display assignments.

def print_province(**province_name):
    for (key, value) in province_name.items():
        print(key + "的简称为: " + value)


print_province(安徽="皖", 重庆="渝", 北京="京", 四川="川")

operation result:
Insert picture description here


1.2.5 Packing and unpacking of variable parameters

Insert picture description here



Guess you like

Origin blog.csdn.net/I_r_o_n_M_a_n/article/details/115253995