Python Forum
Declaring a Global Variable in a Function - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Declaring a Global Variable in a Function (/thread-21115.html)



Declaring a Global Variable in a Function - Bob1948 - Sep-14-2019

I am sorry. I know that this is probably a stupid question. But I am just learning Python and have spent hours trying to figure out what I am doing wrong when trying to declare a global variable in a function. What I am trying to do is modify a variable in the function so that the changed value will be associated with it outside the function. However, when I try to use the variable outside the function it reverts to the initial value set before it was changed, and of course if I don't set an initial value outside the function I get an error saying the variable is not defined. This is a simplified example of what I am trying to understand:

solution = 0

def perform_math():
    global solution
    x = 1
    x = 2
    solution = x + y
    return solution

print(solution)
The program prints 0 instead of 3 when I want it to print 3.


RE: Declaring a Global Variable in a Function - ichabod801 - Sep-14-2019

Well, you never call the function for one thing. Functions don't do anything until you call them. But really, globals are the wrong way to do this. Use return instead:

solution = 0
 
def perform_math(x, y):
    return x + y

solution = perform_math(1, 2)
 
print(solution)



RE: Declaring a Global Variable in a Function - Larz60+ - Sep-14-2019

Don't use globals unless absolutely necessary, it will get you in trouble as your programs grow longer.
pass arguments and return values instead.
Example:

def perform_math(x, y):
    return x + y
print(perform_math(1, 2))
result:
Output:
3



RE: Declaring a Global Variable in a Function - Bob1948 - Sep-14-2019

Thanks to those who replied. The example I posted was too simplified. The actual program is more complicated and uses a command in a gui button to run the function. I think that is where my problem is. I can get the result I want if I return the global variable in the function when using a normal function call. Rather than take up more of your time, I will try to rewrite using a conventional function call.


RE: Declaring a Global Variable in a Function - ichabod801 - Sep-14-2019

With GUIs you should be using classes, and then you can use class attributes to pass variables between methods without using explicit return values.