What is the purpose of global keywords in python?
A global keyword is a keyword that allows a user to modify a variable outside the current scope. It is used to create global variables in Python from a non-global scope, i.e. inside a function. Global keyword is used inside a function only when we want to do assignments or when we want to change a variable. Global is not needed for printing and accessing.
Rules of global keyword:
- If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global.
- Variables that are only referenced inside a function are implicitly global.
- We use a global keyword to use a global variable inside a function.
- There is no need to use global keywords outside a function.
Use of global keyword in Python: To access a global variable inside a function, there is no need to use a global keyword.
Global keyword in Python
In this article, we will cover the global keyword, the basic rules for global keywords in Python, the difference between the local, and global variables, and examples of global keywords in Python.
Contact Us