I'm a programmer coming from Python background which typically uses lexical scoping and I want to understand dynamic scope. I've researched it on-line, still unclear to me. For example, I've read this page which made things a lot easier to me, especially the code snippets:
#In Dynamic scoping:
const int b = 5;
int foo()
{
int a = b + 5;
return a;
}
int bar()
{
int b = 2;
return foo();
}
int main()
{
foo(); // returns 10
bar(); // returns 7
return 0;
}
#In lexical scoping:
const int b = 5;
int foo()
{
int a = b + 5;
return a;
}
int bar()
{
int b = 2;
return foo();
}
int main()
{
foo(); // returns 10
bar(); // returns 10
return 0;
}
As I understand and as you can see, in the dynamic scoping, bar function returns 7 not 10, which means foo called the b variable which is defined within bar, in other words, foo did not looked for the b variable that's defined in top of the code (the first b variable) but rather it used the b variables that's defined in bar.
Q1: Hence, In dynamic scoping, the function that's being called within another function in this case foo called in bar first looks for variables in the caller function in this case bar and then it looks for top level variables ?
Q2: Could you explain dynamic scoping in Python code ?