2.9k views
3 votes
Develop a function called overage loop that accepts any number of numerical arguments and returns their average. Use iteration in this function - Do NOT use the statistics module or the sum() function. Example: average loop(2, 5, 8, 11) should return 6.5.

Demonstrate its use by printing the result of the example above.

User Mowienay
by
8.3k points

1 Answer

1 vote

Final answer:

The 'average_loop' function calculates the average of any number of numerical arguments by iteratively summing the values and counting them. The average is then computed by dividing the total sum by the count of numbers provided.

Step-by-step explanation:

To develop a function called average_loop that accepts any number of numerical arguments and returns their average using iteration, we can write a Python function as follows:

def average_loop(*args):
total = 0
count = 0
for number in args:
total += number
count += 1
return total / count if count > 0 else 0

print(average_loop(2, 5, 8, 11)) # This will output 6.5

The function works by initializing two variables, total and count, to keep track of the sum of the arguments and the number of arguments, respectively. Inside a loop, it adds each number to total and increments count. After the loop, it calculates the average by dividing total by count, provided that count is not zero to prevent division by zero error.

User Lakma Chehani
by
8.2k points