Introduction to using global statements in Python function variables

Source: Internet
Author: User

If you are confused about Python function variables in actual applications, you can read our article. This article mainly introduces how to use global statements in Python function variables, and related functions, the following is the specific content of the article.

Use global statements

If you want to assign a value to a variable defined outside the function, you have to tell Python that the variable name is not local, but global. We use the global statement to complete this function. Without a global statement, it is impossible to assign values to variables defined outside the function.

You can use the value of a variable defined outside the function to assume that there is no variable with the same name in the function ). However, I do not encourage you to do this, and you should avoid it as much as possible, because this makes the reader of the program unclear where the variable is defined. The global statement clearly indicates that the Python function variables are defined in blocks.

Example 7.4 use a global statement

 
 
  1. #!/usr/bin/python  
  2. # Filename: func_global.py  
  3. def func():  
  4. global x  
  5. print 'x is', x  
  6. x = 2 
  7. print 'Changed local x to', x  
  8. x = 50 
  9. func()  
  10. print 'Value of x is', x   
  11.  

Output

 
 
  1. $ python func_global.py  
  2. x is 50  
  3. Changed global x to 2  
  4. Value of x is 2   

How does a Python function variable work? The global statement is used to declare that it is global. Therefore, when we assign a value to a function, this change is also reflected when we use its value in the main block.

You can use the same global statement to specify multiple global variables. The above article introduces how to use global statements in Python function variables.

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.