Python study notes (four)-understanding of functions

1. Define the function

It is recommended to use lowercase for function names, refer to PEP8

Code:

def greet():  #定义函数,注意冒号
    """显示简单的问候语"""   #文档字符串的注释
    print("Hello.")

greet()  
a = greet  #可以给定义的函数指定别名(函数名其实也是对象的引用)
greet()    #调用定义的函数
a()

result:

Hello.
Hello.

2. Passing parameters

When defining a function, you can define the parameters that need to be passed at the same time

Code:

def user_info(name, age):  #定义函数的时候设定需要的参数
    print("名字是:" + name + " 年龄是:" + str(age))  #age是int型,需要转化成字符串

user_info('葫芦娃', 1)  #调用函数时传递参数过去,参数顺序必须相同
# user_info(name='葫芦娃', age=1)  或者用这种直接赋值的方式,这样顺序可以不固定

result:

名字是:葫芦娃 年龄是:1

When defining a function, you can specify the default value of the parameter, that is, when no parameter is passed in when calling, the default value will be used as the unpassed parameter value.

ps: The default parameters must use immutable objects

Code:

def user_info(name, age=1):  #age有默认值
    print("名字是:" + name + " 年龄是:" + str(age))

user_info('葫芦大娃') #没有传入第二个参数
user_info('葫芦二娃')
user_info('蛇精', 100) #有传入参数,则按照传入的参数值执行逻辑

result:

名字是:葫芦大娃 年龄是:1
名字是:葫芦二娃 年龄是:1
名字是:蛇精 年龄是:100

(Note: When defining a function with a default value, the parameter with the default value must be placed behind, such as age above)

Tip: The default parameter must point to an invariant object, not a variable object such as a list or dictionary

Code:

def test(mylist=['s', 's']):
    mylist.append('over')
    return mylist


print (test())  # 第一次调用时候,默认值列表已经创建,变量mylist指向该列表
print (test())  # 第二次调用时,因为列表是可变的,没有产生新对象,所以会在原来列表上继续操作


def grow(name, age=18):
    age = age + 1  # 函数里的+1运算产生了新的对象并由age指向,此时新的age以不是开始时的默认变量age
    # now = age + 1 可换个名字,下面输出语句也要换,就是好理解而已
    print ('name=' + name + '\nage=' + str(age) + '\n')


grow('ZhangSan')  # 第一次调用时,age变量指向的整数是18,是不可变的
grow('ZhangSan')  # 第二次调用时,因为整数是不可变的,所以age变量仍旧是指向整数18(函数里的+1运算产生了新的对象)


#age1和age2不是同一个
age1 = 18   #age1指向整数18
age2 = age1 #age2也指向整数18
age2 = age2 + 1 #因为整数是不可变的,所以age2+1操作后创建了新的对象,age2指向该对象
print (age1 is age2) # 所以age1和age2不同

#list1和list2是同一个
list1 = ['a', 'b']
list2 = list1
list2.append('c') #因为列表是可变的,所以list2.append操作后仍旧是该对象,list2仍旧指向它
print (list1 is list2) # 所以list1和list2相同

result:

['s', 's', 'over']
['s', 's', 'over', 'over']
name=ZhangSan
age=19

name=ZhangSan
age=19

False
True

3. Return value

The function can be used returnto return some data processed by the function, such as lists, dictionaries, strings, etc.

def get_info(first_name, last_name):
    info= first_name + last_name
    return info #此处将处理后的字符串返回

print(get_info('葫芦', '娃'))

result:

葫芦娃

The return value can be multiple, ,separated by. Return as a tuple, for example

Code:

def myadd(x):
    return x, x + 1


a = myadd(1)
print (a)
#a[0] = 20  #此句会报错,因为多个返回值是以元组的方式返回,不可更改
one, two = a #多个变量可同时接收同一个元组,按位置赋值,两边的个数多或少都会报错
print (one)

result:

(1, 2)
1

The return list is equivalent to the return dictionary, just replace the logic in the function body

4. Pass any number of actual parameters

When defining a function, I don’t know how many actual parameters (parameters of the same type) need to be accepted. You can *add a parameter name to indicate that multiple parameters are accepted ( that is, to pass a list, tuple→_→ )

Code:

def cook_food(count, *toppings):  # *toppings表示python创建了一个空元组,并将接收到的值加入到元组中
    """描述要制作的材料"""
    print(str(count) + "份")
    print(toppings)


cook_food(1, '葱', '姜', '蒜')  # 先传固定的实参,再传不固定的参数
cook_food(10, '肉')
mylist = ['葱', '蒜', '鱼', '鸡']
cook_food(1, mylist)  # 此句输出的是一个元组,但只有一个元素列表
cook_food(1, *mylist) # 此句是将参数mylist的所有元素,作为参数依次传递到函数里,输出的元组有四个元素

result:

1份
('葱', '姜', '蒜')
10份
('肉',)
1份
(['葱', '蒜', '鱼', '鸡'],)
1份
('葱', '蒜', '鱼', '鸡')

5. Pass any number of keyword arguments

By **adding parameter names, you can pass multiple keyword arguments ( that is, pass a dictionary and there is no restriction →_→ )

Code:

def build_info(first, last, **user_info):  # **user_info表示,创建一个空字典,并将接收到的键-值对加入到字典中
    """创建一个字典,包含用户的所有信息"""
    info = {}
    info['first_name'] = first  # 添加字段
    info['last_name'] = last
    for key, value in user_info.items():
        info[key] = value
    return info  # 返回字典

#可以封装成字典传入,但是必须加**,例如**dict,不可只传入字典
info = build_info('葫芦', '娃', ability='力气大', 排行=1)
print(info)

result:

{'ability': '力气大', '排行': 1, 'first_name': '葫芦', 'last_name': '娃'}

6, named keyword parameters

Used *as a parameter separator, *the following is the keyword parameter that can only be passed in (the dictionary is passed but there are restrictions →_→ )

Code:

def student(name, age, *, address, tel):  # 命名关键字可以有默认值
    print(name, age, address, tel)


student('Tom', 22, address='china', tel=110)  # 必须传入参数名address 和tel

result:

Tom 22 china 110

Named keyword parameters must be passed in the parameter name, the position order of positional parameters must be fixed, and there is no order for named keyword parameters.

If there is already an arbitrary number of actual parameters in the parameter of the function definition ( note that it cannot be a keyword actual parameter, that is, a dictionary ), the following named keyword parameters no longer need to be *separated. E.g:

Code:

def student(name, age, *otherinfo, address, tel):
    print(name, age, otherinfo, address, tel)


student('Tom', 22, 'nv', 180, address='china', tel=110)

result:

Tom 22 ('nv', 180) china 110

7, recursive function

Like most, call your own function

eg Tower of Hanoi is implemented recursively

def move(n, a, b, c):
    if n == 1:
        print('move', a, '-->', c)
        return
    move(n-1, a, c, b)  # A上的n-1个盘子通过C移动到B
    print('move', a, '-->', c)  # A上最底的盘子移动到C
    move(n-1, b, a, c)  # B上的n-1个盘子通过A移动到C

move(4, 'A', 'B', 'C')

result:

move A --> C
move A --> B
move C --> B
move A --> C
move B --> A
move B --> C
move A --> C

8. Store the function in the module

The function of the function is to separate the logic code block from the main function. The function can be written in other files, and then poured into the file to be used, using the importstatement.

1. Import the entire module ( using import xxxstatement )

Create a .pyfile first

Code:  greet.py

def greet_message():  #定义函数,注意冒号
    """显示简单的问候语"""   #文档字符串的注释
    print("Hello.")

In greet.py create another directory where the .pyfile

Code:  say.py

Code:

import greet  # import语句,整个导入之前写的函数模块
# import greet as gt  # 导入的时候可以用as,指定别名

greet.greet_message() # 使用moudle_name.function_name()的方式调用函数
# gt.greet_message()  # 通过指定的别名,调用函数,指定别名后原模块名就不可用了

2. Import a specific function ( using from xxx import xxxstatement )

The code is the same as above, but replace the import greetstatement with from greet import greet_message and, when calling, you only need to call the function name directly, for example greet_message(), you can also use the asalias to assign the function

Guess you like

Origin blog.csdn.net/weixin_38452841/article/details/108367889