Global Variables

What Is a Global Variable?

  • A global variable in Python is a variable with a scope that extends across the entire program. It can be accessed anywhere, inside or outside functions.

Example of a Global Variable:

  • Here's a simple example of a global variable:

    python
    x = 'hello world - global'
    
    def myFunction():
        print(x)
    
    myFunction()
    print(x)
    
    • Output:

       
      hello world - global
      hello world - global
      
    • In this example, x is a global variable accessible both inside myFunction() and outside in the main program.

Using the global Keyword:

  • When you want to update a global variable inside a function, you need to use the global keyword. Without it, Python will treat the variable as local to the function.

    python
    x = 'hello world - 0'
    
    def myFunction():
        global x
        x = 'hello world - 1'
        print(x)
    
    myFunction()
    print(x)
    
    • Output:

       
      hello world - 1
      hello world - 1
      
    • By declaring x as global inside myFunction(), we ensure the function updates the global variable x rather than creating a new local variable.

Exercises:

  1. Global Variable Access:
    • Create a global variable and access it inside a function and outside the function.

      python
      y = 'global variable example'
      
      def exampleFunction():
          print(y)
      
      exampleFunction()
      print(y)
      
  2. Updating Global Variable:
    • Write a function that updates a global variable.

      python
      z = 5
      
      def updateGlobalVariable():
          global z
          z = 10
      
      updateGlobalVariable()
      print(z)  # Output: 10
      

Summary:

  • Global variables in Python have a scope that spans the entire program. The global keyword is used to modify a global variable inside a function. Practice defining and updating global variables to understand their usage and scope!