In this post, we will learn how to find the average of two numbers using the Python Programming language.
Average is defined as a found by adding all the numbers in a set together and then dividing them by the quantity of numbers in the list.
- Average = Total sum / Total no. of terms
We will use the following approaches to find the average of two numbers:
- Using Standard Method
- Using User-Input
- Using Function
So, without further ado, let’s begin this tutorial.
Python Program to Find Average of Two Numbers
# Python Program to Find Average of Two Numbers # First Number a = 5 # Second Number b = 10 # Calculating average of two numbers avg = (a + b) / 2 # Display output print("Average of two numbers = %.2f" %avg)
Output
Average of two numbers = 7.50
Python Program to Find Average of Two Numbers With User Input
# Python Program to Find Average of Two Numbers With User Input # Asking for input num1 = float(input("Enter the first number: ")) num2 = float(input("Enter the second number: ")) # Calculating average of two numbers avg = (num1 + num2) / 2 # Display output print("Average of two numbers = %.1f" %avg)
Output
Enter the first number: 18
Enter the second number: 24
Average of two numbers = 21.0
How Does This Program Work?
num1 = float(input("Enter the first number: ")) num2 = float(input("Enter the second number: "))
The user is asked to enter two integers. Here, input is taken with the help of the input() function. The float() function is used to convert the input to a floating data type.
# Calculating average of two numbers avg = (num1 + num2) / 2
Then, we find the average of two numbers using the average formula: Average = Total sum / Total no. of terms.
# Display output print("Average of two numbers = %.1f" %avg)
The average of two numbers is displayed on the screen using the print() function. We have used %.1f format specifier to limit the value of average to 1 decimal place.
Python Program to Find Average of Two Numbers Using Function
# Python Program to Find Average of Two Numbers Using Function def average(a, b): return (a + b)/2 # Asking for input num1 = float(input("Enter the first number: ")) num2 = float(input("Enter the second number: ")) # Calling out custom function avg = average(num1, num2) # Display output print("Average of two numbers = %.2f" %avg)
Output
Enter the first number: 7
Enter the second number: 8
Average of two numbers = 7.50
Conclusion
I hope after going through this post, you understand how to find the average of two numbers using the Python Programming language.
If you have any doubt regarding the program, then contact us in the comment section. We will be delighted to assist you.
Also Read: