Variables in Python - AsgarTech


Variables in Python - AsgarTech

 In Python, a variable is a name that refers to a value stored in memory. When you assign a value to a variable, Python creates an object in memory to represent that value, and the variable refers to that object.

Here are some of the basic rules for declaring variables in Python:

  • Variable names must start with a letter or the underscore character (_).
  • Variable names can only contain letters, numbers, and the underscore character (_).
  • Variable names are case-sensitive.
  • Variable names cannot be Python keywords.


The depth of a variable definition in Python refers to the level of nested scope in which the variable is defined. In Python, there are four levels of nested scopes:


Local scope: This is the innermost scope, which includes any variables defined inside a function. Variables defined in this scope are only accessible within the function.


Enclosing scope: This is the scope that encloses the local scope, and includes any variables defined in the function that contains the current function. These variables are accessible in the current function as well as any nested functions.


Global scope: This is the scope that includes any variables defined outside of functions. These variables are accessible anywhere in the module.


Built-in scope: This is the outermost scope, which includes all the built-in functions and types in Python.


The depth of a variable definition refers to the number of levels of nested scope between the current scope and the scope in which the variable was defined. For example, if a variable is defined in the local scope of a function, its depth is 0 in that scope, and its depth is 1 in any nested functions that access it, and so on.


Here of Example of all Variable


x = 1          # variable x is defined in global scope

def outer_func():
    y = 2      # variable y is defined in outer_func's local scope
    
    def inner_func():
        z = 3  # variable z is defined in inner_func's local scope
        
        # depth of z is 0 in inner_func's local scope
        print("z =", z)
        
        # depth of z is 1 in outer_func's local scope
        print("y + z =", y + z)
        
        # depth of z is 2 in global scope
        print("x + y + z =", x + y + z)
        
    inner_func()
    
outer_func()

https://asgartech.blogspot.com/

thanks



No comments: