DEV Community

Scofield Idehen
Scofield Idehen

Posted on • Originally published at blog.learnhub.africa

FInd The Bug Challenge

def calculate_average(numbers):
    total = 0
    count = 0
    for number in numbers:
        total += number
        count += 1
    average = total / count
    return average

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
result = calculate_average(numbers)
print(f"The average is: {result}")
Enter fullscreen mode Exit fullscreen mode

Explanation

The code defines a function called calculate_average that takes a list of numbers as input. It initializes total and count variables to zero. Then, it iterates over the numbers in the list and adds each number to the total variable while incrementing the count by 1.

After the loop, the average is calculated by dividing the total by the count. Finally, the calculated average is printed to the console.

The challenge is to find a tiny mistake in the code that has a significant impact on the output. Your task is to identify and fix the bug to obtain the correct average. Good luck with the bug hunt!

Top comments (8)

Collapse
 
dshaw0004 profile image
Dipankar Shaw

I didn't find any bug. Your Code is returning the average as floating point number, if you want integer then do this
average = total // count

Here is my code

def calculate_average(numbers):
    try:
        avg = sum(numbers)/len(numbers)
    except ZeroDivisionError:
        avg = 0
    return avg

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
result = calculate_average(numbers)
print(f"The average is: {result}")
Enter fullscreen mode Exit fullscreen mode
Collapse
 
scofieldidehen profile image
Scofield Idehen

Correct!!!

//

It was a tiny error but I wanted to see if anyone looks deeply at the detail.

Collapse
 
owentechke profile image
Abraham Gumba

Nowhere does it say that the output should be an integer.

Thread Thread
 
scofieldidehen profile image
Scofield Idehen

if it does then it invalidates the answer

Thread Thread
 
dshaw0004 profile image
Dipankar Shaw

He is right. This is not an error. You should ask "what is the problem here ?"

Then the answer will be -
This code return average as floating point number but user might want integer then we have change the output to integer

Collapse
 
flavius_the_0th profile image
Flavius

Ok i really don't know what the answer and the only thing i came up with was an divided by zero error when passed an empty list. Idk what else

Collapse
 
scofieldidehen profile image
Scofield Idehen

Look again pay attention to dividing it and how.

Collapse
 
uchechiukpa profile image
uchechiukpa

There is no error, code works as expected, averages are usually returned in floating number except stated otherwise.