I'm fairly new to python (been taking classes for a few months) and I've come across a reoccurring problem with my code involving passing information, such as an integer, from one function to another. In this case, I'm having problems with passing "totalPints" from "def getTotal" to "def averagePints" (totalPints in def averagePints defaults to 0).
def main():
endQuery = "n"
while endQuery == "n":
pints = [0] * 7
totalPints = 0
avgPints = 0
option = ""
print("Welcome to the American Red Cross blood drive database.")
print()
print("Please enter 'w' to write new data to the file. Enter 'r' to read data currently on file. Enter 'e' to "
"end the program.")
try:
option = input("Enter w/r/e: ")
except ValueError:
print()
print("Please input only w/r/e")
if option == "w":
print()
def getPints(pints):
index = 0
while index < 7:
pints[index] = input("Input number of Pints of Blood donated for day " str(index 1) ": ")
print(pints)
index = index 1
getPints(pints)
def getTotal(pints, totalPints):
index = 0
while index < 7:
totalPints = totalPints int(pints[index])
index = index 1
print(totalPints)
getTotal(pints, totalPints)
def averagePints(totalPints, avgPints):
avgPints = float(totalPints) / 7
print(avgPints)
averagePints(totalPints, avgPints)
Passing information from "def getPints" to "def getTotal" works fine, and both print the accurate information, but nothing passes from "def getTotal" to "def averagePints" and returns 0. What am I doing wrong in this case? Is it something to do with the scope of the variables listed above?
This is my first time posting to Stack Overflow because I could find any fixes to what I am having troubles with. What I expect to happen from this code is passing the number from "totalPints" in "def getTotal" to "def averagePints" to make a calculation with that number. I tried messing with the scopes of the declared variables and the order of when functions are called but I still can't really tell what I'm missing. All I know is that the value of "totalPints" in "def averagePints" always returns 0.
CodePudding user response:
You have a variable scoping issue. In getTotal, totalPints is being updated with its value local to the function, not the global one like you are expecting. Returning the new value from the function and assigning it seems to have the intended effect. Below is the updated snippet:
def getTotal(pints, totalPints):
index = 0
while index < 7:
totalPints = totalPints int(pints[index])
index = index 1
print(totalPints)
return totalPints
totalPints = getTotal(pints, totalPints)