Search results
If you want to change the values of local variables inside a function you need to use the global keyword.
25 lip 2024 · Any variable which is changed or created inside of a function is local if it hasn’t been declared as a global variable. To tell Python, that we want to use the global variable, we have to use the keyword “global” , as can be seen in the following example:
To change the value of a global variable inside a function, refer to the variable by using the global keyword: x = "awesome" def myfunc (): global x.
global keyword is a built-in keyword in python that you can use to declare a global variable or to change the value of a global variable. Syntax. x = 2. def my_function(): #first call the global variable with global keyword. global x. #then modify its value. x = 8.
Local Variables in Python. In Python, a variable declared inside the body of a function or in the local scope is known as a local variable. Suppose we have the following function: def add_numbers(n1, n2): . result = n1 + n2. Let's try to print the result variable from outside the function. def add_numbers(n1, n2): #local variable .
A variable scope specifies the region where we can access a variable. For example, def add_numbers(): sum = 5 + 4. Here, the sum variable is created inside the function, so it can only be accessed within it (local scope). This type of variable is called a local variable.
If you want to modify a global variable inside a function, then you need to explicitly tell Python to use the global variable rather than creating a new local one. To do this, you can use one of the following: