0

Ok so I've searched the database, and read a few posts, but none of them seem to answer my question, at least in a way I understand. First to premise, I'm new to Python, but have some experience in C# and some C++. In these languages variables are "global" and you can only have one instance of them. Now with python it seems you variables are local, and you can have multiple instances of a variable of same name. For a program I'm having to write for school, I was told using global to pass data is bad practice (don't quite understand that thinking). So I'm trying to pass data from first function to second function. Code as written is using a global variable, however I'm trying to see how I would pass the data b/w them.

    #modules
import time
#variables

testScores = []
#avg = 0.0

#functions
def calculate_average():
    x = 0
    print("Enter test scores")
    while (x <=4): #limits number of inputs to 5 test scores as required per instructions for lab
        test = input('Enter test score: ')
        #if test == "":
            #break
        x += 1
        testScores.append(float(test)) #adds input from test var into testScores list as a float
    time.sleep(1)
    print("","calculating average", ".........", "", sep = "\n")
    time.sleep(1)
    global avg #makes the var avg global so as to keep data stored so other functions can access the data
    avg = float(sum(testScores)/len(testScores))#takes all the data points stored in the list testScores and adds them up via sum ,and then divdes by (len)gth (aka number of data points)
    print("%.2f" % avg)#displays avg limiting to two decimal points rounding to the nearest 100th


def determine_grade(): #fucntion calls the var avg (which was made global in function 1) and converts it into a letter grade.
    if (avg >= 90.0 and avg <= 100.0):
        print("Grade = A")
    elif (avg >= 80.0 and avg <= 89.9):
        print("Grade = B")
    elif (avg >= 70.0 and avg <= 79.9):
        print("Grade = C")
    elif (avg >= 60.0 and avg <= 69.9):
        print("Grade = D")
    elif (avg <= 59.9):
        print("Grade = F")
def main():
    print("Beginning Program","", sep = "\n")
    time.sleep(1)
    calculate_average()
    determine_grade()
    time.sleep(1)
    print("","End of program...", "Have a good day...", "Program Terminated", sep = "\n")

main()

What I need help with is how I can take the value from the variable "avg" in calculate_average() and pass it to determine_grade().

  • 1
    You have to go back and study C++ and C# again. Using global variables is bad practice also in those languages and local variables are very available. – JohanL Jun 26 '17 at 16:51

3 Answers3

0

See: What does return mean in Python?

here is a simple example of executing a function with a return value that is assigned to a variable:

while True:
    avg = calculate_average(testScores)
    grade = determine_grade(avg)
    print(grade)
    time.sleep(1)

update:

related:

jmunsch
  • 22,771
  • 11
  • 93
  • 114
  • Ok so forgive my ignorance, I get what its doing, but how is this a "better" method? You've now created two more variables, vs simply having a single var "avg" (by making it global) and allowing it to be called by functions and update by them as necessary? Seems all you've done (and this whole method) is created greater complexity which allows for higher chance of mistakes – Matthew Harrison Jun 26 '17 at 18:02
0

What you want to do is have calculateAverage() return avg, then pass avg into detrmine_grade()

...
avg = calculate_average()
determine_grade(avg)
...

In calculateAverage instead of

avg = float(sum(testScores)/len(testScores))

do

return float(sum(testScores)/len(testScores))

In determineGrade instead of

def determine_grade():

do

def determine_grade(avg):
0
def calculate_average():
    x = 0
    print("Enter test scores")
    while (x <=4):
        test = input('Enter test score: ')
        x += 1
        testScores.append(float(test))
    time.sleep(1)
    print("","calculating average", ".........", "", sep = "\n")
    time.sleep(1)
    avg = float(sum(testScores)/len(testScores))
    print("%.2f" % avg)
    return avg

def determine_grade(avg):
    if (avg >= 90.0 and avg <= 100.0):
        print("Grade = A")
    elif (avg >= 80.0 and avg <= 89.9):
        print("Grade = B")
    elif (avg >= 70.0 and avg <= 79.9):
        print("Grade = C")
    elif (avg >= 60.0 and avg <= 69.9):
        print("Grade = D")
    elif (avg <= 59.9):
        print("Grade = F")

def main():
    print("Beginning Program","", sep = "\n")
    time.sleep(1)
    avg = calculate_average()
    determine_grade(avg)
    time.sleep(1)
    print("","End of program...", "Have a good day...", "Program Terminated", sep = "\n")
Igor Yudin
  • 393
  • 4
  • 10
  • thank for this worked like a charm, however what I'm struggling with is they why of it all. Why is this way thought to be better vs simply having a global variable. As clearly how I had it worked just fine, vs having multiple instances of the variable having to be created. – Matthew Harrison Jun 26 '17 at 18:21
  • That's a better way for several points. First of all, that's easier to undestand what's going on with a local variable because you don't have to track all its usings which can change its state in unusual way. And that's a good way to manage a program complexity. Secondly, that's cause a tight coupling and that's become really hard to refactor your code when you want to create an independent module or even function. Debugging is also simplier when you don't have to step through all program to undestand why a variable get incorrect value. – Igor Yudin Jun 26 '17 at 20:10