Home » Python

global keyword with example in Python

Python global keyword: Here, we are going to learn about the global keyword with example.
Submitted by IncludeHelp, on April 15, 2019

Python global keyword

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 of global keyword

    global variable_name

Note: Before accessing the global variable outside of the function, function in which global variable is declared must be called.

Example:

    # 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 

Python examples of finally keyword

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


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.