199k views
5 votes
How to turn a local variable global in python

1 Answer

3 votes

Final answer:

To make a local variable global in Python, use the 'global' keyword in the function scope to indicate the variable is global. When you modify the variable inside the function, the global variable's value will be affected.

Step-by-step explanation:

To turn a local variable into a global variable in Python, you can use the global keyword within a function to declare that you want to use the global variable instead of a local one. This tells Python that the variable defined in the scope of a function should be treated as a global variable.

Example:

my_var = 'initial value'

def change_global_var():
global my_var
my_var = 'changed value'

change_global_var()
print(my_var)

In the above example, my_var is defined as a global variable. Inside the function change_global_var, we declare my_var as global, which allows us to change its value within the function scope, and that change will reflect in the global scope afterwards.

User Jdpjamesp
by
8.8k points

No related questions found