Make writing a habit together! This is the sixth day of my participation in the “Gold Digging Day New Plan · April More text Challenge”. Click here for more details.

Definition of function

The function is:

  • Encapsulate the steps of a thing and get the final result
  • The function name represents what the function does
  • The function body is the flow that implements the function
  • Method or function
  • It can be reused

Functions are divided into built-in functions and custom functions. The methods that can be called by each data type mentioned above are all built-in functions. When the built-in functions cannot meet our needs, we need to carry out custom functions

Functions are defined in Python with the keyword def

def func_name(args..)
    todoThe return valueCopy the code

To execute or call a function with a function name ()

Return of the result of the function:

  • Return is the keyword returned by the result of the function
  • Return can only be used inside a function
  • Return supports returning all Python data types
  • A function that has a return value can assign the return value directly to a variable

Customize a capitalize function

def capitalize(data) :
    index = 0
    Save the new string
    temp = ' '

    for item in data:
        # get the first character for the first time
        if index == 0:
            temp = item.upper()
        else:
            temp += item
        index += 1
    return temp


res = capitalize('hello')
print(res)
Copy the code

res = capitalize(123)
print(res)
Copy the code

Defines a function that returns no value

def message(mes, mes_type) :
    new_mes = '[%s]%s' % (mes_type, mes)
    print(new_mes)


message('I am IronMan'.'info')
Copy the code

The function returns None

res = message('Tomorrow is Friday'.'info')
print('res:%s' % res)
Copy the code

Return and print

  • Print simply prints the object and does not support assignment statements
  • A return is a return of the result of a function execution. Assignment statements are also supported

2. Parameters of a function

The parameters of a function are mandatory, default, and indeterminate

Mandatory and default parameters

The parameters defined in the function do not have default values. An error is reported if the function is not passed.

Mandatory parameters have the following characteristics

  • There is no default value in the function. If not, an error will be reported
  • When you define a function, there is no equal sign assigned to the argument
  • When defining a function, parameters that have no default value and must be passed at function execution in the same order as the parameters are required

When you define a function, you assign a default value to the parameter. If the default parameter is given a new value when the function is called, the function takes precedence over the value passed in later.

def add(a, b, c=3) :
    return a + b + c

result = add(1.2)
print(result)

result = add(1.2.6)
print(result)

result = add()
print(result)
Copy the code

Uncertain parameter

Indeterminate parameters are also variable parameters:

  • There is no fixed parameter name and number, and the parameter name is not certain, and the parameter number is not certain
  • * ARgs stands for combining an indefinite number of arguments into tuples
  • **kwargs means to combine statements that have arguments and default values into a dictionary
def alpha(*args, **kwargs) :
    print(args, type(args))
    print(kwargs, type(kwargs))


alpha(1.2.3, name='stark', address='NY')
Copy the code

def bravo(*args, **kwargs) :
    if len(args) > 0:
        for i in args:
            print(i)

    if 'name' in kwargs:
        print(kwargs['name'])

bravo('stark'.'peter'.'banner'.'clint', name='Ming', address='Shanghai')
Copy the code

Pass tuple and dictionary type parameters

tuple_01 = (1.3.5.8.0.11)
dict_01 = {'name': 'stark'.'address':'NY'}

bravo(tuple_01, dict_01)
bravo(*tuple_01, **dict_01)
Copy the code

Parameters of the rules

def alpha(x, y = 1) :
    print(x + y)

# use position to pass parameters
alpha(1.2)

Pass only required parameters
alpha(1)

Use the keyword to pass the parameter
alpha(x = 1, y = 2)

# keyword pass parameter, only mandatory parameter pass
alpha(x = 1)

# the keyword is passed without following the order of the parameters
alpha(y = 1, x = 2)
Copy the code

Mandatory parameters must be passed, otherwise an error will be reported

def bravo(x, y=1, *args) :
    print('x={}, y={}, args={}'.format(x, y, args))


tuple_01 = (1.2)

bravo(1.2, *tuple_01)

This type of parameter transmission will cause an error
bravo(x=1, y=2, *tuple_01)
Copy the code

When required parameters are mixed with default parameters and tuple type parameters, positional parameter transmission is recommended

def charlie(x, y=1, **kwargs) :
    print('x={}, y={}, kwargs={}'.format(x, y, kwargs))


dict_01 = {'name': 'stark'.'address': 'NY'}

charlie(1.2, **dict_01)
# This will cause an error. The positional dictionary must be placed last
# charlie(**dict_01, 1, 2)


charlie(x=1, y=2, name='stark', address='NY')

charlie(name='stark', address='NY', x=1, y=2)
Copy the code

def delta(x, y=1, **kwargs) :
    print('x={}, y={}, kwargs={}'.format(x, y, **kwargs))


dict_01 = {'name': 'stark'.'address': 'NY'}
delta(1.2, **dict_01)
Copy the code

You cannot add * or ** to a function

The type of a function argument

The types of function parameters can be defined as follows

  • Parameter types are defined by parameter name: Parameter data type
  • Python versions later than 3.7 are available
  • Parameter types are not validated
def foxtrot(x:str, y:int=1) :
    print('x={}, y={}'.format(x, y))

foxtrot('stark')

foxtrot('stark'.2)

foxtrot(1.'stark')
Copy the code

def golf(x:str, y:int=1, *args:int, **kwargs:str) :
    print('x={}, y={}, args={}, kwargs={}'.format(x, y, args, kwargs))

golf('stark'.2.1.2, name='stark')

golf(1.3.2.3.id=1)
Copy the code

Global variables and local variables

Global variables are variables defined in the uppermost block of code in a Python script that can be read inside a function but cannot be modified inside a function

name = 'stark'

def hotel() :
    print('The function prints the value of name :', name)

hotel()
print('The value of name printed outside the function is :', name)
Copy the code

Variables defined in the body of a function are called local variables. Local variables can only be used in the body of the currently defined function, not outside the function itself

def iris() :
    address = 'New York'
    print('Function body uses local variables:',address)

iris()
print('Function external using local variables:', address)
Copy the code

Use the global keyword to modify global variables within the body of a function

name = 'stark'

print('The value of name before the function is printed out in vitro is :', name)
def hotel() :
    global name
    name = 'tony stark'
    print(Change the value of name inside the function to:, name)

hotel()
print('The outside of the function again prints the value of name as :', name)
Copy the code

Globa supports only numeric strings, empty types, and Booleans. Dictionary lists do not need the global keyword in the body of a function. It is not recommended to use the global keyword in the body of a function to modify global variables

Recursive function

A function that repeats itself over and over again is called a recursive function

count = 0
def juliet() :
    global count
    count += 1

    ifcount ! =5:
        print('count! If =5, repeat yourself, count is: ', count)
        return juliet()
    else:
        print('the count:,count)

juliet()
Copy the code

Recursive functions that do not have a condition to exit recursion can run out of memory

Anonymous functions

Lambda can define a lightweight function that can be deleted immediately, which is ideal for situations where one function needs to be done, but only used in one place

The definition method of an anonymous function without arguments

f = lambda: value
f()
Copy the code

There are methods for defining parametric anonymous functions

f = lambda x, y: x + y
f(1.2)
Copy the code
kilo = lambda: 1
res = kilo()
print(res)
Copy the code

The content after the lambda colon is what is returned. By default, the return keyword is omitted. An error is reported if the return keyword is added

lima = lambda : print('I am IronMan')
lima()
Copy the code

mike = lambda x, y: x * y
print(mike(9.8))
Copy the code