Global and Local Variables:

Global variables are the variables that are defined and declared outside the the body of a function. We can use it inside a function while coding in python for data science.

Global and Local Variables in Python for Data Science - PST Analytics

In the case of a variable with the same name as define in the scope of the function then, the value inside the function gets print and not the global value.

Global and Local Variables in Python for Data Science - PST Analytics

The variable s is the string variable “PST Analytics for Python”, before calling the function f(). As no local s is available global s will be there.

Let’s change the value of s inside the function f() and see what happens.

For the above program to work global keywords will be require. To change or do assignments, we use global keywords. Python assumes that the any variable change or create inside a function is local in nature if we do not specify it as global. We should use the word “Global” to make the program understand it is a global variable.

Global and Local Variables in Python for Data Science - PST Analytics

Let us look into an example to understand the concept better:

To learn more about python for data science, you can check this and this as well.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.