Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Average of Array

Compute the average of entered list values with Python sum and division. Students distinguish a total from a mean and identify the nonempty-input requirement.

BeginnerPhase 4 - Level 1: Basic ArraysExample 10 of 10
average-of-array.py
1# Take array
2n = int(input("Enter array size: "))
3arr = []
4for i in range(n):
5 arr.append(int(input(f"Element {i+1}: ")))
6
7# Calculate average
8sum_arr = sum(arr)
9average = sum_arr / n
10
11print(f"Average: {average}")

Output

Enter array size: 5
Element 1: 10
Element 2: 20
Element 3: 30
Element 4: 40
Element 5: 50
Average: 30.0

In this one

  • Calculate an arithmetic mean
  • Use true division
  • Recognize undefined empty means

How it works

  1. 1

    Read n integers into arr.

  2. 2

    Compute sum(arr).

  3. 3

    Divide the total by n and print average.

Edge cases

What if n = 0?

What if n = 0?

The average calculation raises ZeroDivisionError.

Why use / rather than //?

Why use / rather than //?

The mean may have a fractional part.

What's going on

sum(arr) adds the collected integers. Dividing that total by n gives the arithmetic mean because the code reads n values.

The / operator can produce a fractional float even when every input is an integer. For two values one and two, the mean is 1.5. A zero-sized input leads to division by zero, so this short exercise assumes a positive count.

What if n = 0? The average calculation raises ZeroDivisionError.

Why use / rather than //? The mean may have a fractional part.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What does sum(arr) supply?

Pick an answer to check it.

Question 2

What if n = 0?

Pick an answer to check it.

Questions people ask

What if n = 0?

The average calculation raises ZeroDivisionError.

Why use / rather than //?

The mean may have a fractional part.

What does sum(arr) supply?

The total of all values.