[Python] study notes 6-functions

What is a function?

In Python, function is a set of related statements that perform a specific task.
Functions help break our program into smaller modular blocks. As our plan gets bigger and bigger, features make it more organized and manageable.
In addition, it avoids duplication and makes code reusable

grammar

def function_name(parameters):
 """docstring"""
 statement(s)  

Shown above is a function definition, which consists of the following components.

The keyword def marks the beginning of the function header.
The name of the function used to uniquely identify it. Function naming follows the same rules for writing identifiers in Python.
Parameters (parameters), we pass the value to the function through it. They are optional.
The colon (:) marks the end of the function header.
An optional docstring used to describe the function of the function.
One or more valid python statements that make up the body of the function. The statements must have the same indentation level (usually 4 spaces).
An optional return statement used to return a value from a function.

How to call the function?

Once we define a function, we can call it from another function, program or even Python prompt. To call a function, we just need to type in the function name with the appropriate parameters

name='Shadow'

def getname(a):
    '''这是一个获取我的名字的函数'''
    print('My name is',a)

getname(name)

result:
Insert picture description here

Docstring

The first string after the function header is called docstring, which is short for docstring. It is used to briefly explain the role of the function.
Although optional, documentation is a good programming practice. Unless you can remember the dinner you ate last week, please record your code.
In the above example, we have a docstring directly below the function header. We usually use triple quotes so that the docstring can be expanded to multiple lines. We can use this string as the __doc__ attribute of the function.

name='Shadow'

def getname(a):
    '''这是一个获取我的名字的函数'''
    print('My name is',a)

getname(name)
print(getname.__doc__)

result:
Insert picture description here

return

name='Shadow'

def getname(a):
    '''这是一个获取我的名字的函数'''
    print('My name is',a)

print(getname(name))


def ifodd(m):
    if m%2==0:
        return 'It is not odd'
    else:
        return 'It is odd'

print(ifodd(10))

result:
Insert picture description here

Scope and lifetime of variables

The scope of the variable is the part of the program that recognizes the variable. The parameters and variables defined in the function are not visible outside. Therefore, they have a local scope.
The life cycle of a variable is the time period during which the variable exits in the memory. The life cycle of the internal variables of the function is as long as the execution time of the function.
They will be destroyed once we return from the function. Therefore, the function does not remember the value of the variable that was previously called.
The following is an example to illustrate the range of variables inside a function.

def my_func():
	x = 10
	print("Value inside function:",x)

x = 20
my_func()
print("Value outside function:",x)

result:
Insert picture description here

parameter

In case one, an error will be reported if the parameter is not given:

def my_func(x):
   print("Value inside function:",x)

my_func()

result:
Insert picture description here

Case 2: Give the default parameters

def my_func(x=11111):
   print("Value inside function:",x)

my_func()

Result:
Insert picture description here
Case 3: There are default parameters and parameters are given

def my_func(x=11111):
   print("Value inside function:",x)

my_func(2222)

result:
Insert picture description here

but

Once we have a default parameter, all the parameters on its right must also have default values.
This means that non-default parameters cannot follow default parameters.
Insert picture description here

def my_func(y=111,x=0):
   print("Value inside function:",y,x)

my_func(2222)

result:
Insert picture description here

Python arbitrary parameters

Sometimes, we don't know the number of parameters that will be passed to the function in advance. Python allows us to handle this situation by calling a function with any number of parameters.
In the function definition, we use an asterisk (*) in front of the parameter name to indicate this kind of parameter. This is an example.

def my_func(*names):

    for name in names:
        print('Hi',name)

my_func(100)

my_func('aaa','bbb','vvv')

result:
Insert picture description here

Python function: remove duplicate objects in the list

def my_func(names):
    empty=[]
    for name in names:
        if name not in empty:
            empty.append(name)
    return empty

print(my_func([1,2,3,4,2,3,7,8,9]))

result:
Insert picture description here

Guess you like

Origin blog.csdn.net/Shadownow/article/details/105842400