Last time, we learned about default parameters to make functions more flexible. But have you noticed something interesting about variables inside functions versus variables outside them?
Engagement Message
Where exactly do variables "live" in our programs?
Variables created inside a function have local scope - they only exist within that function. These local variables are born when the function starts and disappear when it ends.
Engagement Message
What happens to result
after the function finishes?
Local variables can't be accessed from outside their function. This code would cause an error because result
doesn't exist outside the function:
Engagement Message
Why do you think this protection exists?
Variables created outside functions have global scope - they can be accessed from anywhere in the program, including inside functions:
Engagement Message
Can you see how username
is available everywhere?
However, if a function creates a variable with the same name as a global one, the local version takes priority inside that function. The global variable remains unchanged:
