Variables defined within a function are local to that function and cannot be accessed outside the function. Local variables are very loyal to their parent function and live and die with them. Now suppose I define a variable
num1=0 outside functions, it is global. A global variable can be accessed within a function but cannot be modified, unless we declare the variable to be ‘global’ by explicitly mentioning so within the function. eg:
num1 = 5
Variables local to a function cannot be accessed outside a function and will throw an error if we try to do so. Global variables are an easy way to manage handlers without a lot of programming overhead.
Anytime we want to assign a global variable within a function, we must declare it as global in the function. If we try to reference a global variable within a function, without declaring it as global (a mistake obviously), we get an error. However, if we just assign a global variable without declaring it as global (again a mistake ofcourse), Py assumes it is just a local variable and doesn’t throw an error, but the result will be wrong.