Home > Mobile >  How to reuse a variable
How to reuse a variable

Time:08-07

I have the variable total in a function. Say that I'd like to use that variable in an if statement in another function. I can use the return keyword and return that variable from my first function but how would I use that variable in an if statement that would be outside that function or even in a different function?

CodePudding user response:

You could re-declare the variable with the value from the function. I don't have a lot of information, but I think this is what you mean.

def some_function():
    total=10
    return total
total=some_function()
print(total)

CodePudding user response:

return the value from your first function, and then a call to that function will evaluate to that value. You can assign the value to a variable, or pass it directly to another function. In either case, the value doesn't need to be assigned to the same variable name in different scopes.

def func_a():
    total = 42
    return total

def func_b(the_answer):
    if the_answer == 42:
        print("That's the answer to the ultimate question!")

func_b(func_a())
  • Related