Python functions, variable scopes, parameters

Keywords: Python data structure

brief introduction

In programming, we often need to perform the same or similar operations. These operations are completed by a piece of code, and the emergence of functions can help us avoid writing this piece of code repeatedly.
The function is to abstract a relatively independent function and make it an independent entity.
One reason why Python is widely used in the world is that there are a large number of built-in functions in Python, which can help us quickly build various types of websites.

Common built-in functions: max, min, sum, divmod, etc;
Functions must have input and output.

1. How to define and call functions

To define a function, you only need to start with def.

Function name (get_max): the same naming rules as other identifiers in Python. Valid function names start with letters or underscores, followed by alphanumeric and underscores. The function name should reflect the tasks performed by the function.
Note that function names are case sensitive
Function parameters (num1, num2): parameters that can be passed when calling a function. Parameters can be one, more or no parameters.
Function content: any valid code can appear inside the function.
Function return result: the value returned after the function is executed. It can also return nothing. If it does not return anything, it can be regarded as returning "None".

def get_max(num1,num2):
    result = num1 if num1 > num2 else num2
    return result   

Defines a function whose contents are not executed

Call the defined parameters

def get_max(num1,num2):
    result = num1 if num1 > num2 else num2
    return result
max_num = get_max(30,80)

Get return value:

Null function

2. Variable scope

(1) Global variable

Variables created outside the function, variables that take effect globally.

name is created outside the function and is a global variable.

def login():
name = 'admin'

Return to admin

(2) Local variable

Variables created inside a function can only take effect inside a function.

def login():
    name = 'admin'

An error is reported, indicating that name is undefined because name is defined inside the function and is a local variable.

(3) Modify global variables inside functions

When the global variable is an immutable type: the modified variable needs to be declared as a global variable with the global keyword.
When a global variable is a mutable type: no declaration is required.

Variable data types: list, dict, set
Immutable data types: tuple, str, numeric

In the code, changing the value needs to be declared with the global keyword, and changing the list does not need to be declared.

def hello():
    global money
    money += 10
money = 100
users = []

Execution results:

3. Function parameters

Formal parameter: formal parameter, not real value (parameter when defining function)

Argument: the actual parameter, which is the real value (the parameter when calling the function)

(1) Parameter check

isinstance(var,int) determines whether the variable var is of type int

def get_max(num1:int,num2:int)->int:   ##Define the function and annotate the numeric type required by num1 and num2 and the type of return value for prompt
    """                                ##Using three quotation marks will automatically generate the format to write the instructions of the function
    Find the maximum of two numbers
    :param num1:Integer type 1
    :param num2: Integer type 2
    :return: Maximum
    if isinstance(num1,int) and isinstance(num2,int):     ##Judge whether num1 and num2 are integers
        return num1 if num1 > num2 else num2
        return 0
result = get_max(1,2)
result1 = get_max(1,2.1)    ##num2 is not an int

Execution results:

(2) Four common formal parameters

Required parameter

The parameters defined by the function must be called in when calling, and the quantity and order of the call must be consistent with the parameters defined by the function.

Default parameters

Parameters that can be transferred or not

def pow(x,y=2):
    return x ** y    ##y power of x
result = pow(3)
result = pow(2,4)

Execution results:

Variable parameters

The number of parameters will change. You can pass 0, 1, 2, 3... n parameters

Expected keyword * args, args is tuple

def my_sum(*args):

Execution results:

Keyword parameters

kwargs is stored in the dictionary
You can customize the input information in kwargs

def enroll(name,age=18,**kwargs):
    Admission information:
    1,full name:{name}
enroll('Zhang San',country='china',english='GRE',sports=['Basketball','badminton'])

The results are as follows:

4. Expand

Anonymous function

Anonymous functions refer to a class of functions or subroutines that do not need to define identifiers.
python uses lambda syntax to define anonymous functions, requiring only expressions without declarations. (the standard step of declaring functions with def is omitted)

Note: the value before the colon is the input value, and the value after the colon is the output value.

get_max = lambda num1,num2: num1 if num1 > num2 else num2
S = lambda x,y=2: x ** y

The results are as follows:

Topics corresponding to anonymous functions

In fact, it is to reorder the array with anonymous functions, define a sorting rule, and then sort.
[ 0, 7, 0, 2 ]
[ 1, 0, 1 ,0 ]
This means that if the element num in num is equal to 0, Num is equal to 1. If it is not equal to 0, Num is equal to 0
Then use the obtained array to sort again, and finally output. No new number was created.

nums = [0,7,0,2]
nums.sort(key=lambda num:1 if num==0 else 0)

Expansion: even numbers come first and odd numbers come last

nums = [0,7,0,2]
nums.sort(key=lambda num:0 if num % 2 == 0 else 1)

Posted by ghostdog74 on Tue, 16 Nov 2021 07:14:45 -0800