2

After I declare a global variable and it is being modified in a function, I want to replace the default value of this global variable to the one modified after the function call. Is it possible?

1

2 Answers 2

2

A common mistake in python is misunderstanding how to use global - you don't declare the global in the outside scope but in the inside scope, basically confirming for python that you intend to treat the value as a global. An example:

foo = 1

def set_foo(value):
  global foo
  foo = value

print foo  # prints 1
set_foo(2)
print foo  # prints 2

You can see more information in the docs:

https://docs.python.org/release/2.7/reference/simple_stmts.html#global

Sign up to request clarification or add additional context in comments.

Comments

0

Example of using a global variable:

def func1():
    global w
    print(w)
    w = 30


w = 10
func1()    # 10
print(w)   # 30

Comments

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.