How do I use variables defined in one function in another?

Question:

def main():
    i = 0
    intInput = 0
    intCalculate = 0
    while intInput != -999:
        i += 1
        intInput = int(input("How many ounces of water did you drink each day?"))
        Calculate()
    print("You have drank " + str(intCalculate) + " ounces of water")
    print("For " + str(i) + " days")
    print("You drank an average of " + str(float(intCalculate / i)) + " ounces of water")

def Calculate():
    intInput += intCalculate
    return intCalculate

main()

I’m trying to use the calculate function to add the input each time until you type -999 and it stops the loop and prints the results, but I don’t know how to return the values to use them in other functions.

Asked By: Sherbert

||

Answers:

You need to pass it as a parameter. For integers, this means that the function receives a copy of the value, so you can’t modify the original value, unless you encapsulate into something mutable.

It’s easier if you just return the brand new number and replace the original on the caller’s side

def Calculate(intInput, intCalculate):
    intCalculate += intInput
    return intCalculate

Then you’d need to:

intInput = int(input("How many ounces of water did you drink each day?"))
intCalculate = Calculate(intInput, intCalculate)
Answered By: Matias Cicero

You need pass the value to the function and capture the return. If you wanted to add the return from Calculate in the variable intCalculate you would want to do something like this in the line you call the function

intCalculate += Calculate(intInput)

And change the function header to:

Calculate(intCalculate):
    # Code goes here

https://www.learnpython.org/en/Functions

Answered By: jasont41

For the sake of thogoughness you can use global variables.

intInput = 0
intCalculate = 0

def main():
    global intInput, intCalculate

    i = 0
    intInput = 0
    intCalculate = 0
    while intInput != -999:
        i += 1
        intInput = int(input("How many ounces of water did you drink each day?"))
        Calculate()
    print("You have drank " + str(intCalculate) + " ounces of water")
    print("For " + str(i) + " days")
    print("You drank an average of " + str(float(intCalculate / i)) + " ounces of water")

def Calculate():
    global intInput, intCalculate

    intInput += intCalculate
    return intCalculate

main()

But please don’t do this.

Rather, as suggested, pass information via function arguments, or encapsulate state in objects where access to and changes to that state can be controlled via methods.

Answered By: Chris
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.