Difference Between Local and Global Variable in Python

In this python post, you will learn difference between global and local variables in python.

As the name suggests, the global variable can be declared both inside and outside the function in Python. The local variable can be defined inside the only function.

Understand the global and local variables in python with the example. How the local and global variables are defined and how they are used in the Python program.

Local Variable

Which variables are made inside the function in python. They are called local variables. Local variables can be used only inside the function in python.

For example:

def valfun():
   x = "great"
   print("Python is " + x)
 valfun()

Global Variable

Which variables are made outside the function. They are called global variables. Global variables can be used both inside and outside the function in python.

Declaring global variables in python without using global keyword

For example:

x = "great"
 def valfun():
   print("Python is " + x)
 valfun()

Declaring global variables in python using global keyword

Generally, when you create a variable in python inside any function, that is local variable. And you can not use this variable outside of the function.

You can create/define a global variable inside the function by using the global keyword.

For example:

def valfun():
   global x
   x = "powerful"
 valfun()
 print("Python is " + x)

AuthorDevendra Dode

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

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