+ 2
what os the different between global variable and local variable
5 Answers
+ 7
local variables are inaccessible out of the scope. Global variables are common in anywhere of the program
+ 6
In Java it looks like this if you can relate.
Global Variable
int x = 0;
for(;x<1;++x){x is Global}
___________________________
Local Variable
for(int x= 1; x<1;++x){x is Local}
+ 3
Globals you can use in anywhere in your code
Locals only where you defined its, for example into a function
+ 2
If you define a local variable in a function sum() for example then you cant use values of that in a function div()
+ 1
When you define a variable it is local by default. If you want call it inside a function, you must define as global.
For example:
#I'll ask the user a number
num = int (input ())
#Now I will do something with this number
def do_something ():
result = num + int (1)
do_something ()
print (do_something)
>>> Erro.
Why ????
Because num is local defined (default). To use it inside a function, you must define as global, it is, visible for everyone.
#I'll ask the user a number again
num = int (input ())
#Now I will do something with this number, but I'll define num as global
def do_something ():
global num
result = num + int (1)
do_something ()
print (do_something)
>>> 2 (if input was 1)
# ~~~~~~~~~~~~~~~~~~~ #
My English isn't good, but I've tried explain with my best. To read more about, check this out:
https://www.python-course.eu/python3_global_vs_local_variables.php