Global Variables
A global variable is a variable defined outside of any function, making it accessible from anywhere in the program, including from within functions.
Global vs Local Variables
A variable created inside a function is called a local variable and only exists while that function is running. A variable created outside all functions, at the top level of a script, is a global variable and remains accessible throughout the program's execution.
course_name = "Data Science" # global variable
def show_course():
print("Course:", course_name) # can read the global variable
show_course()
Reading vs Modifying Global Variables
A function can freely read a global variable's value without any special syntax. However, if you try to modify a global variable's value inside a function without additional steps, Python will treat it as a new local variable instead.
global keyword, which is covered in detail in the next topic.Coming Up Next
Next, you'll learn exactly how the global keyword allows a function to modify a global variable's value directly.