How to parse Python function variables

Source: Internet
Author: User

If you want to knowPythonHow function variables work related practical application skills can be found in our articlePythonThe following describes how to use function variables.

How Python function variables work

When we use the value of x for the first time in a function, Python uses the value of the form parameter declared by the function. Next, we assign value 2 to x. X is the local variable of the function. Therefore, when we change the value of x in the function, the x defined in the main block is not affected. In the last print statement, we prove that the value of x in the main block is indeed not affected.

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 

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.