How to make a variable global python

Find out how to make a variable accessible to all functions in Python using the keyword 'Global'.

Making a Variable Global in Python

Python is a powerful programming language that offers a wide range of features for developers. One of the most useful features is the ability to declare variables as global. By doing this, you can access the variable from any scope, allowing you to access and modify it from any part of your code.

In Python, you can declare a variable as global by using the global keyword. Here is an example of declaring a global variable:


x = 5

def my_function():
    global x
    x = 10

print(x) # 5

my_function()
print(x) # 10

In the code above, we have declared a variable x with the value of 5. Then, in the function my_function, we declared x as a global variable using the global keyword. This makes it accessible from outside the function. When we call the my_function function, the value of x is changed to 10. When we print the value of x after calling the function, we can see that it has been changed to 10.

Using the global keyword is a great way to make a variable accessible from anywhere in your code. It can be very useful when you need to share a variable among different functions or modules.

Answers (0)