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



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



Topic: Functions and their scopes in Python. Create user functions 
What is Python Scope?
In Python, variables are just not accessible from the class they have been declared in. To know where variables exist in a program and how to access them depends on how they have been declared. The part of the program where variables, functions, and objects are easily accessible is commonly referred to as scope in Python.
Types of Scopes in Python:
In Python, there are four types of scopes, which are as follows:  

  • Global Scope

  • Local Scope 

  • Enclosing Scope

  • Built-in Scope

Global Scope (with example)
Global scope refers to the names of variables which are defined in the main body of a program. These are visible and accessed throughout the program. The variables or objects declared in the global scope are easily accessible to all functions within the program. Let’s understand the global scope with the help of a code.
message = "Hey"
def python_developer():
developer = "Welcome to Python Programming!"
print(message, developer)
def developer_name(name):
print(message, name)
python_developer()
developer_name("Mark!")
OUTPUT:
Hey Welcome to Python Programming!
Hey Mark!
Copy Code
Attention: As a good programming habit, it is advisable to avoid global variables as much as possible. Why? Because they are easy to alter and the result could be erroneous output. Global variables increase the security vulnerability of the code as well. That doesn’t mean you will not use global variables at all. As a thumb rule, try to use those variables and objects in the global scope, which are meant to be explicitly used globally like functions and objects. 
Local Scope
Local scope refers to the names which are defined within a function and are local to that function. They can be accessed from the point of its definition until the end of the block in which it has been defined. The local scope exists till the time the function has been executed. Let’s understand the local scope with the help of a code.
def local_test():
value = 1
# Print statement 1
print("The value defined is: ", value)
local_test()
OUTPUT:
The value defines is: 1
Copy Code
Notice the error if you run the following code.
def local_test():
value = 1
print("The first number defined is: ", value)
OUTPUT:
Traceback (most recent call last):
File "C:/Projects/untitled/basic.py", line 4, in
print("The value defined is: ", value)
NameError: name 'value' is not defined
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