Topic: Functions and their scopes in Python. Create user functions What is Python Scope?


Enclosing Scope or Non-local Scope



Yüklə 41,02 Kb.
səhifə2/5
tarix24.10.2023
ölçüsü41,02 Kb.
#130884
1   2   3   4   5
Topic2

Enclosing Scope or Non-local Scope
Enclosing scope is also known as non-local scope. They refer to the names of a variable defined in the nested function. Simply put, these variables are neither present in the local scope nor in the global scope. To create a non-local variable in an enclosing scope, use a non-local keyword. Let’s understand the enclosing scope with the help of a code.
def parent_nest():
initial_value = 5
def child_nest():
next_value = 10
print("Value defined in the parent function: ", initial_value)
print("Value defined in the parent function: ", next_value)
child_nest()
parent_nest()
OUTPUT:
Value defined in the parent function : 5
Value defined in the parent function : 10
Copy Code
Built-in Scope
When the variable or object is not found in local, global, or enclosing scope, then Python starts looking for it in the built-in scope. Built-in scopes are one of the widest scopes that cover all the reserved keywords. These are easy to call anywhere in the program prior to using them, without the need to define them.

As we move towards more complex use of scope in Python, we recommend our python programming learning online, which you can follow while applying these concepts in real python projects. 
Modifying the Behavior of a Python Scope
Python scope's behavior is strict. Though python allows accessibility to global names from anywhere, their modification is highly restricted. With the help of allowed keywords, you can modify the behavior of a Python scope. The two keywords allowed in Python to modify the behavior of a Python scope are:

  1. Global Keyword

  2. Local keyword

Global Keyword
To define a variable declared inside a function as global, we have to use the ‘global’ keyword. By using a global keyword followed by a variable name, you are asking Python to use the globally defined variable instead of creating a local variable. Let’s understand this concept with a code snippet. 
You are free to use multiple global statements with a name. All the names that you list in a global statement will be automatically mapped to the global scope in which you define them. Let us understand how to use a global keyword with the help of a code.
message = "Hey"
def python_developer():
global message1
message1 = "Welcome to Python Programming!"
print("In Function message is: ", message)
python_developer()
print("Outside Function message is: ", message1)
message
print("Message is: ", message)
OUTPUT:
In Function message is: Hey
Outside Function message is: Welcome to Python Programming!
Message is: Hey
Copy Code

Yüklə 41,02 Kb.

Dostları ilə paylaş:
1   2   3   4   5




Verilənlər bazası müəlliflik hüququ ilə müdafiə olunur ©muhaz.org 2024
rəhbərliyinə müraciət

gir | qeydiyyatdan keç
    Ana səhifə


yükləyin