Average of two numbers in Python
Simple Python code for calculating the average of two numbers
Calculating the average of numbers is a fundamental concept in mathematics and programming. In Python, this can be done easily using built-in functions and loops. This guide will walk you through a simple Python program to compute the average of two or more numbers.
The average of a set of numbers is obtained by summing all the numbers and then dividing the total by the count of numbers. The formula for the average is:
Average = (Sum of all elements) / (Total number of elements)
Below is a Python program that calculates the average of user-input numbers:
# Taking input for the number of elements
n = int(input("Enter the number of elements to be inserted: "))
# Initializing an empty list to store numbers
arr = []
# Loop to get user input and store in list
for i in range(0, n):
elem = int(input("Enter element: "))
arr.append(elem)
# Calculating the average
avg = sum(arr) / n
# Displaying the result rounded to two decimal places
print("Average of elements which you entered:", round(avg, 2))
Enter the number of elements to be inserted: 3
Enter element: 10
Enter element: 20
Enter element: 50
Average of elements which you entered: 26.67
Python allows us to write concise code using list comprehension. Below is an optimized version of the program:
n = int(input("Enter the number of elements: "))
arr = [int(input("Enter element: ")) for _ in range(n)]
print("Average:", round(sum(arr) / n, 2))
Calculating the average of numbers in Python is simple and can be done using loops or list comprehension. By understanding the logic behind averaging and implementing it in Python, beginners can strengthen their foundational programming skills. Try modifying the program to calculate weighted averages or handle decimal inputs for further practice!
Pro Tip: Use the statistics.mean()
function from Python’s statistics
module for a built-in solution.
This simplest example of python program , as beginner you must execute this program.
Here we are taking a input as number .the range of number is n .
Enter value which is you want to Sum and we are using loop to sum all number and then divide total for finding average of given input :
Below is code for average of two or more numbers :
n=int(input("Enter the number of elements to be inserted: ")) arr=[] for i in range(0,n): elem=int(input("Enter element: ")) arr.append(elem) avg=sum(arr)/n print("Average of elements which you are entered ",round(avg,2))
Enter the number of elements to be inserted: 3 Enter element: 10 Enter element: 20 Enter element: 50 Average of elements : 40