Local and global variables in Python

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:

global num1
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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s