第六章(4):Python的函数———作用域(scope)
作用域
Python has two types of function scope:
1.Local Scope:
- Variables defined within a function are considered to be in the local scope of that function.
- These variables are not accessible outside of the function.
- They only exist during the execution of the function and are deleted once the function finishes executing.
2.Global Scope:
- Variables defined outside of any function are considered to be in the global scope.
- These variables are accessible from anywhere within the program.
- They exist for the entire lifetime of the program.
When a variable is accessed within a function, Python first looks for it in the local scope. If it is not found in the local scope, Python then looks for it in the global scope.
所谓作用域,就是一个变量可被访问的范围。,通常情况下,一个变量的作用域是由其在代码中被赋值的位置决定的。