At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.
A variable declared outside of a function is considered global within the function. A variable declared within a function is considered local within the function. global_name = 'fred' global_surname = 'smith' def func_of_sorts(): local_surname = 'bloggs' global global_surname, global_name print global_name, global_surname print global_name, local_surname func_of_sorts() # call your function print global_name, global_surname print global_name, local_surname I can only use global_name and global_surname in my function because of line 'global global_surname, global_name'. The result of the above will be: fred smith fred bloggs fred smith fred Traceback (most recent call last): File "/home/andy/Ubuntu One/ELearning/MOOC/Week 4/global_variable_test.py", line 13, in
print global_name, local_surname
NameError: name 'local_surname' is not defined
The reason is because the compiler does not have local_surname defined in the main block, only in the function.
Hope this helps.
I want to ask that what happens inside the compiler(in c or c++)...... How will compiler trace that given variable is global or local(its scope)
I am no compiler expert. :-) I would assume that it is due to scopes yes. Regards
bro.. what do you think of compiler? compiler works as a parser which converts the source code into object code. so compiler will know about given variable from its declaration. and if you thinking what happens at execution time then it's defferent things
yes, I want to know what happens at execution time........
first of all execution of a program is not the work of compiler. the compiled code can be executed without the help of compiler. the compiled prog is linked with appropriate lib and loaded in the appropriate place in memory. so local and global variables are located at different places in the main memory (RAM). local variable is generally present in stack of the process.