Practical 6: Program to Calculate the Sum and Average of the First 10 Natural Numbers
Problem Statement
Write a Python program to calculate the sum and average of the first 10 natural numbers (1 to 10).
The program should:
- Calculate the sum of the first 10 numbers.
- Calculate the average of those 10 numbers.
- Print both the sum and the average.
Solution Code
# Program to calculate the sum and average of the first 10 numbers
# Defining the range of numbers
numbers = range(1, 11) # Numbers from 1 to 10
# Calculate the sum of the numbers
total_sum = sum(numbers)
# Calculate the average of the numbers
average = total_sum / len(numbers)
# Output the sum and average
print(f"The sum of the first 10 numbers is: {total_sum}")
print(f"The average of the first 10 numbers is: {average}")
Output
- The program will calculate the sum and average of the first 10 natural numbers and print them.
Example output:
The sum of the first 10 numbers is: 55
The average of the first 10 numbers is: 5.5
Process finished with exit code 0
Explanation
Below is the explanation of F.E. PPS Unit 2 Practical 6 solution where we have written Python program to calculate the sum and average of the first 10 natural numbers (1 to 10).
- Defining the Numbers Range:
- The program defines the range of numbers from 1 to 10 using Python’s range() function. range(1, 11) generates numbers from 1 to 10.
- Calculating the Sum:
- The sum() function is used to calculate the sum of the numbers in the range. It adds up all the values in the sequence from 1 to 10.
- Calculating the Average:
- The average is calculated by dividing the sum by the number of elements in the list. Since we are calculating the sum of the first 10 natural numbers, the length of the range is len(numbers), which equals 10.
- The formula for the average is: average=sum of numbersnumber of numbers\text{average} = \frac{\text{sum of numbers}}{\text{number of numbers}}
- Displaying the Result:
- The program then prints the sum and the average of the numbers.
Key Concept Learned
- Using range() for Sequences:
- The program demonstrates how to use the range() function to generate a sequence of numbers within a specified range.
- Using Built-in Functions (sum() and len()):
- The sum() function is used to calculate the total sum of a sequence, and the len() function is used to find the number of elements in the sequence, both of which are essential for this practical.
- Arithmetic Operations:
- This program emphasizes basic arithmetic operations like addition and division to calculate the sum and average.
- Displaying Results:
- The program uses print() to display the final sum and average, a key concept when interacting with the user or providing output.