Variable Scope

primeteacher32 737 views 7 slides Mar 14, 2018
Slide 1
Slide 1 of 7
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7

About This Presentation

Variable Scope


Slide Content

Variable Scope

Variable Scope: Local and Global Scope refers to the visibility of objects. In other words which parts of your application can see it or use it. Variables defined inside a function are local to that function. They are hidden from the statements in other functions, which normally cannot access them. When the function terminates the values are released. Question: What is another situation where the variable was only known while the structure was executing? Because the variables defined in a function are hidden, other functions may have separate, distinct variables with the same name. However, do not let this confuse you. Question: What does the above statement mean?

Local Variables A function’s local variables exist only while the function is executing. This is known as the lifetime of a local variable. When the function begins, its local variables and its parameter variables are created in memory, and when the function ends, the local variables and parameter variables are destroyed. This means that any value stored in a local variable is lost between function calls and posts.

Global Variables and Global Constants A global variable is any variable defined outside all the functions in a program. The scope of a global variable is the portion of the program from the variable definition to the end. This means that a global variable can be accessed by all functions that are defined after the global variable is defined. Bad Programming: The use of global variables Good Programming: Only creating global variables that are constant, passing variables through functions

Updating a Global Variable Code: Updating a global variable: globVar = < val > def functionName (): global globVar globVar = <new value> Why: Without the keyword global inside the function referencing the global variable, the function would just crate a local variable.

Scope Examples

Scope Examples
Tags