Python variable scope

Source: Internet
Author: User
Tags variable scope

There are four types of Python for scopes: buildin scope, global scope (module scope or file scope), high-level function scope, and local scope.

Where the Buildin scope is the Python built-in scope, which was established when Python was initialized;

The global scope is the scope of the variable directly defined in the file;

The scope of the high-level function is the scope of the local variables defined in the outer function;

Local scope is the scope of local variables defined inside the function;

In the Python language, the position where the variable is assigned is the scope in which the variable is located.

Python searches for a variable first from the local scope, finds the upper function scope, the global scope, and the Buildin scope if it is not found, and throws an exception if the lookup has no results.

Therefore, the variable assignment statement in the inner layer overrides the outer variable definition.

If you need to modify the global variables in the inner layer, then you need the global statement to declare the scope of the variable.

Python variable scope

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.