# What is global Keyword in Python?

In Python, variables can be declared in two main scopes: **global** and **local**. Global variables are accessible from anywhere in the code, while local variables are only accessible within the function or block where they are defined.

Python has the `"global"` keyword, which allows users to modify global variables from within the local scope.

## What is global Keyword?

Let's understand with an example.

```python
# Example of "global" keyword

# Global variable
var = "declared as global"

def modify_var():
    # Function's scope
    global var
    # Modified the global variable "var"
    var = "modified global"
    print(var)

modify_var()
print(var)
```

In this example, the global variable `var` is defined first, followed by the function `modify_var()`.

Inside the `modify_var()` function, the `global var` statement is used to reference the global variable `var` in the function's scope and then the variable `var` is modified and printed.

The function is then called. Upon running the code, you'll get the following result.

```bash
modified global
modified global
```

You can observe that the global variable `var` is modified.

In conclusion, **the** `global` **keyword is used to reference and modify a global variable within the scope of a function**.

## Not Using global Keyword

What happens if you do not use the `global` keyword and attempt to modify a global variable within the local scope?

```python
# Global variable
var = "declared as global"

def modify_var():
    # Function's scope
    # Trying to modify the global variable "var"
    var = "modified global"
    print(var)

modify_var()
print(var)
```

In this example, the `global var` statement is removed from the function and an attempt is made to modify the variable `var`.

```bash
modified global
declared as global
```

You can observe that the global variable `var` remains unchanged.

## Making Local Variable a Global One

The `global` keyword can also be used to create a global variable in the local context.

```python
def separate():
    text = "Geek Python"
    print(text.split(" "))

separate()
print(text)
```

In this example, the `text` variable is declared within the `separate()` function and has scope within the function only.

The `text` variable is being accessed outside of the function scope. This will result in an error.

```bash
['Geek', 'Python']
Traceback (most recent call last):
  ...
    print(text)
          ^^^^
NameError: name 'text' is not defined. Did you mean: 'next'?
```

When you add a global statement just above the `text` variable, it becomes the global variable, which may be accessed from anywhere in the code.

```python
def separate():
    global text   # Added global stmt
    text = "Geek Python"
    print(text.split(" "))

separate()
print(text)
```

When you run the code, you'll get the value stored in the `text` variable.

## Assigning Value to the Global Variable Within Local Scope

Consider the following example which attempts to change the global variable within the local scope without using the global statement.

```python
# Global variable
initial = 2

def increment():
    for x in range(10):
        # Assigning value to the global var in local context
        initial += x

increment()
print(initial)
```

A global variable named `initial` is declared and initialized with the value 2.

The function named `increment()` increments the global variable `initial`. The function is then called and the value of the `initial` variable is printed.

When you run the code, you'll get the following result.

```bash
Traceback (most recent call last):
  ...
    increment()
  ...
    initial += x
    ^^^^^^^
UnboundLocalError: cannot access local variable 'initial' where it is not associated with a value
```

The error message indicates that the local variable `"initial"` cannot be accessed. Python interprets the function's `initial` variable as a new local variable, which is why the code failed to locate the `initial` variable within the function's scope and returned an error.

However, when you add a global statement (`global initial`) within the function, Python will know that it is now referencing the existing global variable within the local scope.

```python
# Global variable
initial = 2

def increment():
    global initial
    for x in range(10):
        # Assigning value to the global var in local context
        initial += x

increment()
print(initial)
```

You won't get an error when you run the code as the global statement has been added to the function scope.

```bash
47
```

## Conclusion

The `global` keyword can be used to reference and modify an existing global variable within a local scope. If the global variable does not already exist, the `global` keyword can be used to create it within the local scope of a function.

---

🏆**Other articles you might be interested in if you liked this one**

✅[Yield Keyword in Python with Examples](https://geekpython.in/yield-keyword-in-python)?

✅[Best Practices: Positional and Keyword Arguments in Python](https://geekpython.in/positional-and-keyword-arguments-in-python)

✅[Python's \_\_getitem\_\_ method](https://geekpython.in/python-getitem-method)?

✅[Create a WebSocket Server and Client in Python](https://geekpython.in/build-websocket-server-and-client-using-python).

✅[Create and Interact with MySQL Database in Python](https://geekpython.in/mysql-database-in-python)

✅[Understanding the Different Uses of the Asterisk(\*) in Python](https://geekpython.in/asterisk-in-python)?

---

**That's all for now**

**Keep Coding✌✌**
