Python Tutorials
Python File Handling
Python Modules
Variables are only available within the built-in region. This is called width.
The variables created within the function are based on the local scope of that function, and can only be used within that function.
A variable created inside a function is available inside that function:
def myfunc():
x = 300
print(x)
myfunc()
As described in the example above, variable x is not found outside the function, but is available in any function within the function:
The local variable can be accessed from a function within the function:
def myfunc():
x = 300
def myinnerfunc():
print(x)
myinnerfunc()
myfunc()
The variables created by the Python coding body are global variables and are of global scope.
Global variables are available anywhere, global and local.
A variable created outside of a function is global and can be used by anyone:
x = 300
def myfunc():
print(x)
myfunc()
print(x)
If you use the same dynamic word in and out of work, Python will treat them as two different variables, one available worldwide (outside of work) and one available locally (within-function):
The function will print the local x, and then the code will print the global x:
x = 300
def myfunc():
x = 200
print(x)
myfunc()
print(x)
If you need to create a global variable, but stick to a wide area, you can use a global keyword.
Global keyword makes dynamics more global.
If you use the global keyword, the variable belongs to the global scope:
def myfunc():
global x
x = 300
myfunc()
print(x)
Also, use a global keyword if you want to make a change in the global variable within a function.
To change the value of a global variable inside a function, refer to the variable by using the global keyword:
x = 300
def myfunc():
global x
x = 200
myfunc()
print(x)