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.
1# Take array2n = int(input("Enter array size: "))3arr = []4for i in range(n):5 arr.append(int(input(f"Element {i+1}: ")))67# Calculate average8sum_arr = sum(arr)9average = sum_arr / n1011print(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
Read n integers into arr.
- 2
Compute sum(arr).
- 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.
๐Related Content
- ๐
Phase 4 - Learn Concepts
Review Phase 4 concepts and explanations
- ๐
Phase 4 - Quiz
Test your Phase 4 understanding with quiz questions
- ๐ป
Phase 4 - All Practice Problems
Explore all practice problems for Phase 4
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum