Python Forum

Full Version: unexpected output for global variable
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,
I am a beginner in python.
I am trying to use a global variable in local namespace i.e. within a function.The program is following:

def my_func():
	global my_var
	print my_var
	my_var=10
my_var=20
my_func()
print my_var * 5
Output:
20 50
The second output is creating little confusion.i think this should simply multiply my_var's value 20 with 5.
Why it is taking my_var's value 10 here?
This is one of the reasons why global variables are frowned upon and should never be used.

Since the variable is global, the second you execute my_func, you override the global with the value 10, so setting it to 20
is never seen.

This also demonstrates part of a situation that can leave to a very un-easy problem to find. where two functions are setting the value
of my_var, creating a situation of who's on base.

Instead of using a global, pass the desired value as an argument to the function.