0

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

1
  • If you know you are working with a global variable, you don't want or need a parameter in the function. Commented Jul 5, 2022 at 12:56

5 Answers 5

1

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)
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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

Comments

1

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.

Comments

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

some_function(Variable)
Variable = x
print(Variable)

1 Comment

Please don't just post the code, you should also include explanation why provided solution works.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.