Function
-If you want to reuse the same or very similar functions, write a function.
-function uses the DEF keyword declaration to return a value with the return keyword
def my_function(x, y, z=1.5): if z > 1: return z * (x + y) else: return z / (x + y)
-Returns None if no return at the end
-functions can have positional parameters and keyword arguments, keyword elaboration is usually used to specify default values or optional parameters, in the above code x and Y are positional parameters, and z is the keyword parameter, can be called in the following two methods
a = my_function(5,6,z=0.7)c = my_function(5,6,0.7)d = my_function(4,8)
-the keyword parameter must be located after the position parameter (if there is a positional parameter), you can specify the keyword parameter in any order
* Note: You can also pass positional parameters with keyword parameters. The previous example can be written as
c = my_function(x=5,y=6,z=0.7)
namespaces, scopes, and local variables
-The function is happy to access the variables of two different scopes: global variable and local variable (local).
-python called namespaces
-The following function
def func(): a = [] for i in range(5): a.append(i)
-After Func is called, the empty list A is created first, then 5 elements are added, and a is destroyed when the function exits
-If we define a as follows
a = []def func(): for i in range(5): a.append(i)
-Although you can assign a global variable to a function, those variables must be declared as global variables with the GLOBALS keyword to
global a
Return multiple values
def f(): a = 5 b = 6 c = 7 return a,b,ca,b,c = f()print(a)print(b)print(c)
-The above code returns a ternary tuple
-You can also write the following code to return a dictionary
def f(): a = 5 b = 6 c = 7 return {"a":a,"b":b,"c":c}a= f()print(a)
Data analysis with Python-2