The return value of the function and scope

1, the function returns the value

def func(name,age,country):
    user_info = {}
    user_info['name'] = name
    user_info['age'] = age
    user_info['country'] = country
    return user_info


my_user_info = func('xu', 10, 'CN')

Note:
    1, in the face of the function return statement, it will stop performing the function and value of return, namely return statement on behalf of the function execution ends
    2, if there are no function return statement, it will default return None

    If you want to return multiple values: when using the return user_info, country return multiple values, the value returned is in the form of tuples returned.

2. Scope

= name " Xu Cool " 
DEF FUNC (): 
    name = " dashuaibi " 
    Print ( " inside name: " , name) 


FUNC () 
Print ( " outside name: " , name)

Print result: Inside name: dashuaibi
        outside name: xu cool

Why the name change function which, when output name on the outside, and did not change it?

    1, variables are defined in a function called local variables, the variable a defined at the beginning in a program called global variables.

    2, the global variable scope (i.e. the effective range) is the entire program, the local variable is a function of the variable scope of the definition.

    3, the search order is variable local variable> Global Variables

    4, when the global variables and local variables of the same name in the function definition of local variables, local variables play a role; global variables to function elsewhere.

    5, in the function is not directly modify global variables

in order to modify global variables inside a function, you will need to declare a global variable inside the function: global name = "xu dashuaige"


phenomenon 3, the transfer list, occurs when the dictionary
   in modify global variables inside a function and a list of dictionaries, dictionaries and external list will change accordingly.
   Because the program is just a list, and dictionary memory address passed to the function, the equivalent value is passed a container, the container was not something passed to the function. So things can change container.

Guess you like

Origin www.cnblogs.com/zrxu/p/11577976.html