scope in python

SCOPE

SCOPE:

variables can only reach a area in which they are defined this is called scope in python. Think of it as the area of code where variables can be used . Python supports global variables and local variables.

By default, all variables declared in a function are local variables. To access a global variable inside a function, it’s required to explicitly define ‘global variable’.

Example

Below we’ll see the use of local variables and scope. This code  will not work:
def function(a,b):
print('You called function(a,b) with the value x = ' + str(a) + ' and y = ' + str(b))
 print('a * b = ' + str(a*b))
  = 4 # cannot reach p, so THIS WON'T WORK

p= 3
function(5,2)


this example will not work the example down will work :


def function(a,b):
    p = 3
    print('You called function(a,b) with the value a = ' + str(x) + ' and b = ' + str(y))
    print('a * b = ' + str(a*b))
    print(p) # can reach because variable z is defined in the function 

function(5,2)



lets learn it more further :


def a(b,,c,d):
    return b+c+d # this will return the sum because all variables are passed as parameters

sum = function(2,5,10)
print(sum)


CALLING FUNCTIONS IN FUNCTIONS:


We can also get the contents of a variable from another function:


def function_one():
    return 5

def function_2(a,b):
    z = function_one() # we get the variable contents from highFive()
    return a+b+z # returns x+y+z. z is reachable becaue it is defined above

result = function_2(3,2)
print(result)


remember : 


If a variable can be reached anywhere in the code is called a global variable. If a variable is known only inside the scope, we call it a local variable.



anonymous-
happy learning!



Image result for thanks for watching gif😏😏

Comments

Popular posts from this blog

wifi attack with kali linux

how to clone a simcard ???