Introduction and usage of functions in Python

Keywords: Python Pycharm

1. Introduction to functions

When developing a program, a piece of code needs to be written many times, but in order to improve the efficiency of writing and code reuse, the code block with independent functions is organized into a small module, which is function

Rules for defining functions:

  1. The function code block begins with the def keyword, followed by the function identifier name and parentheses ().
  2. Any incoming parameters and arguments must be placed between parentheses, which can be used to define parameters.
  3. The first line of the function can optionally use a document string - used to hold the function description.
  4. The function content starts with a colon: and is indented.
  5. Return [expression] ends the function and selectively returns a value to the caller. A return without an expression is equivalent to returning None.

2. Function definition and call

The format is as follows:

def Function name():
    Execute statement
 Function name()    #Call function


def info():
    print("Life is short, I use it python")

After the function is defined, it is equivalent to having a code with certain functions. If you want these codes to be executed, you need to call it
Calling the function is very simple. You can complete the call through the function name ()
Every time a function is called, the function will be executed from the beginning. When the code in this function is executed, it means that the call is over
Of course, if return is executed in the function, the function will also end

3. Parameters of function

1. First define a function with parameters and call this function


def test1(a,b):   # a. B is the parameter
test1(1,2)  # When calling a function with parameters, you need to pass data in parentheses

The parameters in parentheses during definition are used to receive parameters, which are called "formal parameters"
When calling, the parameters in parentheses are used to pass to the function, which are called "arguments"

4. Classification of parameters

There are four types of function parameters:
	Position parameters
	Keyword parameters
	Default parameters
	Indefinite length parameter

1. Position parameters

The format is as follows:

def Function name(Parameter 1,Parameter 2):
    Code block
 Function name(Value 1,Value 2)


def fun(a,b):

2. Keyword parameters

The format is as follows:

def Function name(Parameter 1,Parameter 2):
    Code block
 Function name(Parameter 1=Value 1,Parameter 2=Value 2)


def fun(a,b):

The parameter transfer order can be changed during parameter call. If there are location parameters, the location parameters need to be placed in front of the keyword parameters


def fun(a,b):

If the keyword parameter is passed before the location parameter, an error will be reported


def fun(a,b):

3. Default parameters

Parameters with default values in formal parameters are called default parameters (also called default parameters)


def printinfo(name,age=20):

When calling a function, if the value of the default parameter is not passed in, the default value (formal parameter) is taken. If it is passed in, the actual parameter is taken
The default parameter must be at the end of the location parameter

4. Variable length parameters

Sometimes a function may be required to handle more parameters than originally declared. These parameters are called variable length parameters and will not be named when declared.

The format is as follows:

def printinfo(*args,**kwargs):

The variable args with an asterisk (*) will store all unnamed variable parameters. Args is a tuple
The variable kwargs with * * will store named parameters, i.e. parameters with the shape of key=value. Kwargs is a dictionary

01. Variable length parameter * args


def printinfo(*args):

02. Variable length parameter * * kwargs


def printinfo(**kwargs):
printinfo(a=100,b=200,c=300,d= 400)

5. Function position sequence

The format is as follows:

def fun(Position parameters,*args,Default parameters,**kwargs):
    Code block
fun(Parameter value)


def sun(a,*args,b=22,**kwargs):
    print("a: ",a)
    print("args: ",args)
    print("b: ",b)
    print("kwargs: ",kwargs)

If many values are variable length parameters, in this case, you can put the default parameter after * args, but if there is * * kwargs, * * kwargs must be the last

6. Return value of function

I gave my son 10 yuan to buy me a pack of cigarettes. In this example, I gave 10 yuan to my son, which is equivalent to passing the parameter when calling the function to let my son buy cigarettes. The ultimate goal is to let him bring the cigarettes back to you and give them to you. Right,,, at this time, the cigarettes are the return value

The format is as follows:

def sum():
    Code block
    return value


def sum(a,b):
    return a+b
result = sum(1,2)   #Save the return value of the function

1. Multiple return s


def create_nums(num):
    if num == 100:
        return num + 1  # The following code in the function will not be executed, because return has a hidden function besides returning data: ending the function
        print("return Execution will not continue after execution")
        return "Input is not 100"

There can be multiple return statements in a function, but as long as one return statement is executed, the function will end, so the subsequent return is useless

2. Return multiple data


def divid(a, b):
    add = a+b    #Add
    reduct = a-b    #subtract 
    return add, reduct  #The default is tuple
result = divid(5, 2)

Return can be followed by tuples, lists, dictionaries, etc. as long as it is a type that can store multiple data, you can return multiple data at one time

7. Type of function

Functions can be combined with each other according to whether there are parameters and return values. There are four types:
1. No parameter, no return value
2. No parameter, return value
3. There are parameters but no return value
4. There are parameters and return values

1. Functions without parameters and return values

This kind of function cannot receive parameters and has no return value. Generally, this kind of function is used for functions similar to the print prompt lamp


def printMenu():
    print('      xx Shabu Shabu ordering system')
    print('  1.  Mutton Shabu Shabu')
    print('  2.  Beef Shabu Shabu')
    print('  3.  Pork Shabu Shabu')

2. Functions with no parameters and return values

This kind of function cannot receive parameters, but it can return some data. Generally, this kind of function is used to collect data


def getTemperature():
    # Here are some processing procedures for obtaining temperature
    # For simplicity, first simulate the return of a data
    return 24

3. Functions with parameters and no return value

This kind of function can receive parameters, but can not return data. Generally, this kind of function is used when setting data for some variables without results

4. Functions with parameters and return values

This kind of function can not only receive parameters, but also return some data. Generally, this kind of function is used for applications such as data processing and requiring results


# Calculate the cumulative sum of 1~num
def calculateNum(num):
    result = 0
    i = 1
    while i<=num:
        result = result + i
    return result

8. Function nesting

Another function is called in one function, which is the so-called function nested call


def testb():
    print("testb start")
    print("testb testb  implement")
    print("testb end")
def testa():
    print("testa start")
    print("testa end")

If the function A calls another function B, then the task in the function B will be executed before the last function A is executed.

9. Anonymous function

lambda function is also called anonymous function, that is, the function has no specific name


g = lambda x :x+1

lambda functions can be assigned to variables and are returned by default, so there is no need to add the return keyword
For example, g = lambda x:x+1 can be regarded as the following function. Before the colon is a parameter. There can be multiple, separated by commas, and the return value to the right of the colon

def g(x):
    return x + 1

Posted by lenhewitt on Sun, 26 Sep 2021 03:00:31 -0700