Not getting the correct result for my output in average function

Question:

I’ve been working on do loops for python although there isn’t one for the language. I am trying to get the average of certain integers entered until a negative integer is entered. I was able to get the program working, instead it gives me the wrong results after entering the numbers and getting the average. For instance, if I provide a set of 5 numbers, and then enter a negative number to calculate it, it gives me an answer of 1.0. I would like some advice on how to get rid of this issue to get the accurate answers for finding the average from the 5 set of numbers entered.

Will process and calculate the average
totalScore = 0
getTestScore: int = 0
total = getTestScore + 1
count = getTestScore
count: int = count + 1
totalScore = getTestScore()
averageTestScore = float(totalScore) / count

return averageTestScore

    # Do loop function
    total = 0
    count = 0
    totalTestScore = total + 1
    average = calculateAverage(totalTestScore, count)
    while True:    #This simulates a Do Loop
        testScore = getTestScore()
        totalTestScore = total + 1
        count = count + 1
        if not(testScore >= 0): break   #Exit loop
    calculateAverage(totalTestScore, count)
    
    return average

I’m unsure of where I went wrong to get the same answer, 1.0 for every different number I enter.

I tried changing around the positions of where they were on the line and how they were indented to make sure it was corrects. The program plan I wrote is very simple and I’m trying not to drastically change it to not match my program plan.

Asked By: china.c

||

Answers:

You’re initializing the variable named average as below code

{average = calculateAverage(totalTestScore, count)}

But you aren’t overwriting it or saving any new value into it. At the end you’re returning the value of that variable that has retained the same value since it was initialized.

Answered By: Ali Ozery
def average(x):
    total = 0
    count = 0
    for i in x:
        count += 1
        total += i
    return total/count
        

lst = []
num_input = int(input("enter the numbers"))
while num_input >= 0:  # This simulates a Do Loop
    lst.append(num_input)
    num_input = int(input("enter the numbers"))   
#print(lst) 

average(lst)     
Answered By: Sefa_Kurtuldu

After exiting the loop you were not updating the existing average variable. So in order to get the correct result you need to add average = calculateAverage(totalTestScore, count) after exiting loop line

Answered By: 0xSatya