A variable is only available from inside the block of code where it is created. The block is called the scope of the variable.
- variable can be accessed inside the block of the code
- if variable created inside function then it can be accessed inside the function only
def square_of_num(num): npow = 2 return print(square_of_num(10)) # output: 100
npowcan be accessed inside function only otherwise it will throw
npowis called as local variable
Function Inside Function¶
- the local variable can be accessed from a function within the function.
- lets look at the below code
* when the code is executed it returns the value of the variable
def func(): x = 300 def inner(): return x return inner() output = func() print(output) # output: 300
- a variable created in the main body of the python code is a global variable and belongs to the global scope.
- global variables are available from within any scope, global and local.
x = 100 def func(): print(x) func() # output: 100 print(x) # output: 100
- same variable name can be used in both local and global scopes.
- gobal scope varible can't be overridden by the local variable.
name = "Anji" def change_name(): name = "Avtar" print(name) change_name() # output: "Avtar" print(name) # output: "Anji"
- global variable value can be udated inside the function by using the
name = "Anji" def change_name(): global name name = "Avtar" print(name) change_name() # output: "Avtar" print(name) # output: "Avtar"