In this tutorial, you will learn to write a Python program to find average of n numbers.
The average of n numbers is the sum of those n numbers divided by n.
For example, the average of 1, 2, 3, 4, and 5 is (1+2+3+4+5)/5 = 3.
To understand this program you should have an understanding of the following topics:
1: Python Program To Find Average Of n Numbers Using While Loop
n = int(input("Enter the number of elements to be inserted: "))
sum = 0
i = 1
while i <= n:
num = float(input("Enter element " + str(i) + ": "))
sum += num
i += 1
avg = sum / n
print("Average of", n, "numbers is: ", avg)
Output
Enter the number of elements to be inserted: 4
Enter element 1: 4
Enter element 2: 8
Enter element 3: 12
Enter element 4: 16
Average of 4 numbers is: 10.0
In this program, we first take input from the user to determine the number of elements to be inserted.
We then use a while loop to take input for each element and add it to a running sum.
After all elements have been added, we calculate the average by dividing the sum by the number of elements and print the result.
2: Python Program To Find Average Of n Numbers Using For Loop
n = int(input("Enter the number of elements to be inserted: "))
sum = 0
for i in range(1, n+1):
num = float(input("Enter element " + str(i) + ": "))
sum += num
avg = sum / n
print("Average of", n, "numbers is: ", avg)
Output
Enter the number of elements to be inserted: 5
Enter element 1: 5
Enter element 2: 10
Enter element 3: 15
Enter element 4: 20
Enter element 5: 25
Average of 5 numbers is: 15.0
In this program, we first take input from the user to determine the number of elements to be inserted.
We then use a for loop to take input for each element and add it to a running sum.
After all elements have been added, we calculate the average by dividing the sum by the number of elements and print the result.
Discover more from Python Mania
Subscribe to get the latest posts sent to your email.