Local and Global Variables
Learn about the concept of local and global variables in a programming language.
We'll cover the following...
Local variables
A variable declared (or created) inside a function is called a local variable, and it can only be accessed from within the function. Outside the function, it’s as if the variable never existed at all. Take a look at the following code:
def my_function():name = "Lisa"my_function()print name
Here, we create and assign a value to the name
variable inside the my_function
function. Outside the function, we first call the function, and then we try to print the name. The program will crash with an error on the line where we try to print the name. The reason is because the name
variable is unknown in this part of the program. It’s only valid as long as we execute code inside the function.
This is a local variable. It’s local because it’s been created inside the function.
If we instead change the program so it looks like ...