0

I am attempting to turn my code into def functions for an assignment. I have defined the functions and I have called to them in the main function. However, the code does not function. The error displayed is Traceback (most recent call last): File "C:\Users\iamep\Desktop\Python Projects\TestAvgCalc2-1.py", line 31, in average = total / total_quiz ZeroDivisionError: division by zero

I believe I need to assign global variables. How would I do this?

Here is the Code:

#Welcome Message
print("Welcome to the Test Average Calculator!")
print("Say 'stop' when you are done with Data Entry")

#Variables
total = 0
total_quiz = 0

def testAvgCalculation():
    while True:
    #User Input and Variable to stop loop
        inpt = input("Enter score: ")
        if inpt.lower()== 'stop':
            break
    #Data Validation
        try:
            if int(inpt) in range(1,101):
                 total += int(inpt)
                 total_quiz += 1
            else:
                print("Score too small or Big")
        except ValueError:
            print("Not a Number")
#Average Calculation
average = total / total_quiz

def displayAverage():
    #Display Average and amount of test scores input
    print('The Average score is: ', format(average, '.2f'))
    print('You have entered', total_quiz, 'scores')
#Main Function
def main():
    testAvgCalculation()
    displayAverage()
#Run Main Function
main()
Flamonga
  • 37
  • 5

2 Answers2

2

Please don't use global mutable variables.

Create the variables in the function, and pass them around.

def testAvgCalculation():

    #Variables
    total = 0
    total_quiz = 0
    # rest of the code
    return total, total_quizz

# nothing here

def displayAverage(total, total_quizz):
    # you can do the calculation here
    average = total / total_quiz
    # use the same code to print



def main():
    total, total_quizz = testAvgCalculation()
    displayAverage(total, total_quizz)

main()
LotB
  • 461
  • 4
  • 10
1

Scoping is incorrect.

some = 22

def func():
    some = 10
    print(some)   # 10


func()
print(some)  

prints

 10
 22

because the outer scope some is uneffected by the inner function some.

So all you do in your testAvgCalculation(): does not effect the outer scope variables and they stay 0 - so you can not divide by them.

You can use the global keyword (advising against it) or return the data outside:

def func(myvar):
    myvar + = 5
    return myvar

g = 22
g = func(g) # now g is 27 

because it is provided to the function, modified and returned and reassigned


Read more about scoping here: Short description of the scoping rules?

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69