Home > Enterprise >  How to change the global value of a parameter when using a function in python
How to change the global value of a parameter when using a function in python

Time:07-06

This is what I want to achieve

Variable=0
Some_function(Variable)
print (Variable)

I want the output to be 1 (or anything else but 0)

I tried using global by defining some_function like this, but it gave me an error "name 'Variable' is parameter and global"

def Some_function(Variable):
    x=Variable 1
    global Variable
    Variable=x

CodePudding user response:

You are using Variable as your global variable and as function parameter.

Try:

def Some_function(Var):
    x=Var 1
    global Variable
    Variable=x

Variable=0
Some_function(Variable)
print (Variable)

CodePudding user response:

You should not use the same name for parameter and the globale variable

CodePudding user response:

The error message seem clear enough. Also, you wouldn't need to pass Variable as a parameter if you are using a global.

If you define

def f():
    global x
    x  = 1

Then the following script should not output an error :

x = 1 # global
f(x)
print(x) # outputs 2

Another possibility :

def f(y):
    return y 1

Which you can use like this :

x = 1
x = f(x)
print(x) # 2

CodePudding user response:

If you want to modify global variable, you should not use that name as function parameter.

var = 0

def some_func():
    global var
    var  = 1

some_func()
print(var)

Just use global keyword and modify variable you like.

CodePudding user response:

Variable = 0
def some_function(Variable):
    global x
    x = Variable   1

some_function(Variable)
Variable = x
print(Variable)
  • Related