06-local and global variables, 06-global variables

Source: Internet
Author: User

06-local and global variables, 06-global variables
Local variable: The variable defined in the function. It is only used in the current function, but not in other functions.

In [1]: def test1 (): # define a test1 function...: a = 100 # value assignment...: In [2]: def test2 (): # define a test2 function...: print ("a = % d" % a) # print...:
In [4]: test1 () # Call the test1 function. Because there is no return, the result is null In [5]: test2 () # Call the test2 function, error reported when NameError Traceback (most recent call last) <ipython-input-5-35ebc1c532fc> in <module> () ----> 1 test2 () <ipython-input-2-d9ea9e4cdd20> in test2 () 1 def test2 (): ----> 2 print ("a = % d" % a) 3 NameError: name 'A' is not defined # indicates that a is not defined. a is a local variable defined in the test1 function.
Global variables: defined outside the function and can be used in any function.
In [1]: a = 99 # variables defined outside the function can be used In any function [2]: def test1 ():...: a = 100...: print ("test1 function a = % d" % )...: In [3]: def test2 ():...: print ("test2 function a = % d" % )...: In [4]: test1 () test1 function a = 100In [5]: test2 () test2 function a = 99

Why is the value of a in the test1 function 100 printed? When the program is running, it starts to call the function and looks for local variables first. If no global variables are found

Global # declare global variables
Root @ ubuntu:/home/python/codes/python basics-05 # cat! $ Cat 03-Get temperature. pywendu = 30 # define a global variable wendudef get_wendu (): wendu = 33 # modify wendu def print_wendu (): print ("the temperature at this time is % d" % wendu) # print get_wendu () # Call the function print_wendu () # Call the function root @ ubuntu:/home/python/codes/python basics-05 # python3! $ Python3 03-get the temperature. py at this time, the temperature is 30 # The result is 30.

Why is that? Obviously, the global variable wendu has been modified in the function, but the result is still 30? If the wendu variable has been defined at the position of the global variable and you want to modify the global variable in the function, it is not enough for wendu to be a value, in this case, the wendu variable is a local variable, which is just the same as the global variable name. The Modification result is as follows:

Root @ ubuntu:/home/python/codes/python basics-05 # cat! $ Cat 03-Get temperature. pywendu = 30def get_wendu (): global wendu # global wendu is used to declare a global variable. Then wendu = 33 is to modify the global variable wendu = 33def print_wendu (): print ("the temperature is % d" % wendu) get_wendu () print_wendu () root @ ubuntu:/home/python/codes/python basics-05 # python3! $ Python3 03-get the temperature. py the temperature is 33 at this time.

When the local variable name is the same as the global variable name, the local variable is selected. The default value is definition, and the global variable is modification.

Location defined by global variables

1. Put a variable before the definition function ***

2. Before calling a function

Function documentation

Let's take a look at our own defined functions:

In [1]: def test():   ...:     print("abcdefg")   ...:     In [2]: help(test)Help on function test in module __main__:test()

Nothing is explained. The code we wrote today may be known today, but we forgot it after a long time. How can we solve this problem? We need to describe the function documentation, let's take a look at the built-in functions:

In [3]: help(print)Help on built-in function print in module builtins:print(...)    print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)        Prints the values to a stream, or to sys.stdout by default.    Optional keyword arguments:    file:  a file-like object (stream); defaults to the current sys.stdout.    sep:   string inserted between values, default a space.    end:   string appended after the last value, default a newline.    flush: whether to forcibly flush the stream.

As you can see, print has a document description, so let's add a document description for the test function:

In [4]: def test ():...: '''print string''' # This instructs us to develop a good habit of writing comments...: print ("abcdef ")...: In [5]: help (test) Help on function test in module _ main __: test () print string
List and dictionary as global variables

If the list is used as a global variable, you can use it directly without adding global, because in python, the list and dictionary are of variable type.

Root @ ubuntu:/home/python/codes/python basics-05 # cat test. py #-*-coding: UTF-8-*-nums = [11,22, 33] infor = {"name": "laowang", "age": 16} def test1 (): nums. append (44) infor ['addr '] = "henan" def test2 (): print (nums) print (infor) test1 () test2 () root @ ubuntu: /home/python/codes/python basics-05 # python3 test. py [11, 22, 33, 44] {'addr ': 'henanc', 'age': 16, 'name': 'laowang '}

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.