How do I declare a global variable in Python class?


A global variable is a variable with global scope, meaning that it is visible and accessible throughout the program, unless shadowed. The set of all global variables is known as the global environment or global scope of the program.

We declare a variable global by using the keyword global before a variable. All variables have the scope of the block, where they are declared and defined in. They can only be used after the point of their declaration.

Example

Example of global variable declaration

def f():    
        global s    
        print(s)    
        s = "Only in spring, but Miami is great as well!"
         print(s)
s = "I am looking for a course in New York!"  
f()
print(s)

Output

I am looking for a course in New York!
Only in spring, but Miami is great as well!
Only in spring, but Miami is great as well!

Updated on: 09-Sep-2023

10K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements