How to use local variable in a function and return it?

function, python, return, variables

Solution

Functions shouldn't have to know what scope they're called from; the point of a function is to make a re-usable block of code that can be invoked multiple times from different places.

You communicate information to a function by passing it through its input variables. The function communicates information back to its caller by returning it.

Managing the variables of a scope is the job of the code in that scope not any functions it invokes. If you need to set variables to values determined by a function, then you have the function return those values and you use them to set the variables. If the values the function is calculating depend on the values of variables you have in the calling scope, then you need to pass them to the function as arguments. The function you're calling shouldn't have to know what variables you're using, and shouldn't be able to mess with them.

Putting that all together, what you want to do is something like this:

def find_chamber_discard(chambersinreactor, cardsdiscarded):
    chambersinreactor += 1
    cardsdiscarded += 1
    return (chambersinreactor, cardsdiscarded)

chambersinreactor = 0;
cardsdiscarded = 0;

chambersinreactor, cardsdiscarded = find_chamber_discard(chambersinreactor, cardsdiscarded)

print chambersinreactor
print cardsdiscarded

There are ways to get around this with global variables or manipulating mutable data structures, but ultimately they make your program less flexible and more likely to contain errors that will be difficult to spot. There is a place for those techniques, but the first method you reach for to communicate information to and from functions really should be passing arguments and receiving return values.

Problem

I am trying to create a script that sets a local variable, references it from a function, and can return the manipulated value back to the main scope (or whatever it's called; I'm new to Python) I have simplified my code to show the utmost basics of what I am trying to accomplish, which is to import a local from the module into a function block, I think. I have gotten this to work by using `globals`, but that isn't the best solution . . . ``` chambersinreactor = 0; cardsdiscarded = 0; def find_chamber_discard(): """Find chambers and discard in row (reads each player slot)""" chambersinreactor = 0; # Resets the variable, not what I want cardsdiscarded = 0; # Resets the variable, not what I want chambersinreactor += 1 cardsdiscarded += 1 return # Don't know what to put here find_chamber_discard() print chambersinreactor # prints as 0, should be 1 print cardsdiscarded # prints as 0, should be 1 ```

Original source