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

example:

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

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

example:

def test1(a,b):   # a. B is the parameter
    c=a+b
    print(c)
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)

example:

def fun(a,b):
    print("a:",a)
    print("b:",b)
fun(2,3)


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)

example:

def fun(a,b):
    print("a:",a)
    print("b:",b)
fun(a=2,b=3)

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

example:

def fun(a,b):
    print("a:",a)
    print("b:",b)
fun(3,b=2)

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

example:

def fun(a,b):
    print("a:",a)
    print("b:",b)
fun(a=3,2)


3. Default parameters

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

example:

def printinfo(name,age=20):
    print("name:",name)
    print("age:",age)
printinfo(name="jack")

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):
    print("args:",args)
    print("kwargs:",kwargs)
printinfo(parameter)

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

example:

def printinfo(*args):
    print("args:",args)
printinfo(100,200,300,400)


02. Variable length parameter * * kwargs

example:

def printinfo(**kwargs):
    print("kwargs:",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)

example:

def sun(a,*args,b=22,**kwargs):
    print("a: ",a)
    print("args: ",args)
    print("b: ",b)
    print("kwargs: ",kwargs)
sun(100,200,300,b=2,m=3,n=4)

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

Scenario:
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
sum()

example:

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


1. Multiple return s

example:

def create_nums(num):
    print("---1---")
    if num == 100:
        print("---2---")
        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")
    else:
        print("wewe")
        return "Input is not 100"
print(create_nums(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

example:

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

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

example:

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

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

example:

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


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

example:

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


8. Function nesting

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

example:

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

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

example:

g = lambda x :x+1
print(g(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
print(g(1))

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