Home »
Python
Python global Keyword
By IncludeHelp Last updated : December 07, 2024
Description and Usage
The global is a keyword (case-sensitive) in python, it is used to declare a global variable inside a function (from a non-global scope).
As we know that variables are accessible within the same scope in which they are declared but a global variable can be accessed within a program anywhere. In python, we can define a global variable inside a function or in a non-global using by using global keyword.
Syntax
Syntax of global keyword:
global variable_name
Nore
Before accessing the global variable outside of the function, function in which global variable is declared must be called.
Sample Input/Output
# function
def myfunc():
# global variable
global a
# assigning the value to a
a = 10
# main code
# function call
myfunc()
print("outside the function a: ", a)
Output:
outside the function a: 10
Example 1
Declare a global variable inside a function, assign the value after the declaration, and print the value inside and outside of the function.
# python code to demonstrate example of
# gloabl keyword
# function
def myfunc():
# global variable
global a
# assigning the value to a
a = 10
# printing the value
print("inside myfunc() a: ", a)
# main code
# function call
myfunc()
print("outside the function a: ", a)
Output
inside myfunc() a: 10
outside the function a: 10
Example 2
# Declare a global variable
counter = 0
def increment():
global counter # Access the global variable
counter += 1
print(f"Counter inside function: {counter}")
# Call the function
increment()
# Check the value of the global variable
print(f"Counter outside function: {counter}")
Output
Counter inside function: 1
Counter outside function: 1