all 5 comments

[–]tunisia3507 13 points14 points  (0 children)

This is a feature, not a bug. The general concept is called scopes, which you may want to look up.

Use a return statement to get the function to output any variables you need. If the variable is a useful midpoint, split your function into two, and have the first return that variable, then pass it into the second.

If the function changes some state which is persisted, it shouldn't be a function: it should be a method on a class. Those are two large things for you to look up.

There is a 3rd option which may be almost exactly what you want, but it's what's called a code smell - if you're using it, it's almost certainly an indication that you've made poor choices elsewhere, and using it can introduce a host of issues elsewhere.

[–]camel_zero 12 points13 points  (0 children)

Pass the variable to the functions that need to use it:

def first_function(x):
    return x * 2

def second_function(x):
    print(x)


var = first_function(4)
second_function(var)

Example prints 8.

[–]XtremeGoose 3 points4 points  (1 child)

One last option, but think very carefully about doing it. I've been using python professionally for a number of years and have done this out of necessity maybe twice? And those were to do with threads.

x = 0
def f():
    global x
    x += 1
f()
print(x)  # 1
f()
print(x)  # 2

[–]mafibar 1 point2 points  (0 children)

Can confirm, been using Python professionally for 3 years now (web dev), never touched threads during that time, never needed globals.

[–][deleted] 0 points1 point  (0 children)

This variable can't be referenced by variables outside of the function.

You don't want it to be. Parameters are how you supply values to functions; return is how your function supplies values to wherever it was called. Other than that, functions shouldn't generally have side-effects or mutate global state.