Have you ever wondered where variables live and how long they stick around in your programs? Just like how we sometimes have private thoughts and public announcements, variables in programming can be private (local) to a specific part of your program or public (global) for the whole program to access.
This lesson will uncover the mysteries behind these concepts. Ready to dive deep? Let's go.
In programming, the term scope refers to the region of the program where a variable can be accessed. Not all variables are accessible from every part of our program, and sometimes, this is a good thing! It helps keep our code organized and error-free.
Local variables are variables that are defined inside a function and cannot be accessed outside of that function. Their "lifetime" or duration of existence is only as long as the function is running.
from microbit import *
def show_message():
message = "Hello from inside the function!"
display.scroll(message)
show_message()
# display.scroll(message) # This would cause an error, as 'message' is local to the function.
Here, the variable message
is local to the show_message()
function. If you try to access it outside of the function, Python will raise an error.
message
variable outside of the show_message()
function.To create a new Python project for a Microbit, open the website python.microbit.org.
This will open the code editor with a new project. It might have some example code already added such as:
# Imports go at the top
from microbit import *
# Code in a 'while True:' loop repeats forever
while True:
display.show(Image.HEART)
sleep(1000)
display.scroll('Hello')
You should delete this code except for the import
line that you will need. This imports the necessary libraries you will need to code a microbit.
# Imports go at the top
from microbit import *
Global variables are defined outside of all functions and can be accessed from any part of the program, including inside functions (provided we use the global
keyword within the function).
from microbit import *
global_variable = "I am global!"
def display_global():
global global_variable # we need to include this so we can access global_variable inside the function
display.scroll(global_variable)
display_global() # This will display the global variable's value.
Here, global_variable
is accessible both outside and inside of our function.
It's important to use global variables sparingly. Overusing them can make your code harder to understand and debug. Local variables, being confined to their functions, often make your intentions clearer and your code more organized.