Python Forum

Full Version: Globals vs Function
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Is using a function like this to define variables ok? 
def variables(a, b):
    a = something
    b = another

def some_function():
    do something with variables(a).
    do something with variables(b).
What is the difference between using a function to define variables and just using globals like this?
a = something
b = another

def some_function():
    do something with a.
    do something with b.
Hello!
If you want to do something with outer to the function variables it's better to pass them as parameters.

num1 = 44
num2 = 55

def addition(a, b):
    returnt a + b

result = addition(num1, num2)
print(result)
Output:
99
Variables defined within the function are local to this function and exist as long as the function is running.
When you are using global variables in a local scope, you are cross scope boundaries. This can become confusing and hard to track. If you run into a problem with the values of a and b, it can be harder to figure out where a and b are being modified. If you are passing them around as parameters and return values, it becomes easier to track down where they might get modified.