Your task today is to write a program that calculates the average of a list of numbers provided by the user. This is a fundamental mathematical operation, and implementing it will help you practice working with lists, loops, and arithmetic operations.
For example:
10, 20, 30, 40
25.0
Calculating averages is a common operation in various fields like:
This challenge will help you solidify concepts like:
# Prompt the user for input
numbers = input("Enter a list of numbers separated by spaces: ").split()
# Convert input to a list of floats
numbers = [float(num) for num in numbers]
# Calculate the average
average = sum(numbers) / len(numbers)
# Display the result
print(f"The average is: {average:.2f}")
# Function to calculate average
def calculate_average():
try:
# Prompt the user for input
numbers = input("Enter a list of numbers separated by spaces: ").split()
# Convert input to a list of floats
numbers = [float(num) for num in numbers]
# Calculate and display the average
average = sum(numbers) / len(numbers)
print(f"The average is: {average:.2f}")
except ValueError:
print("Invalid input. Please enter numeric values only.")
except ZeroDivisionError:
print("No numbers provided. Please enter at least one number.")
# Call the function
calculate_average()
import java.util.Scanner;
public class AverageCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Prompt the user for input
System.out.print("Enter a list of numbers separated by spaces: ");
String input = scanner.nextLine();
// Split input and convert to array of numbers
String[] inputNumbers = input.split(" ");
double sum = 0;
int count = inputNumbers.length;
for (String number : inputNumbers) {
sum += Double.parseDouble(number);
}
// Calculate and display the average
double average = sum / count;
System.out.printf("The average is: %.2f\n", average);
}
}
import java.util.Scanner;
public class AverageCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
// Prompt the user for input
System.out.print("Enter a list of numbers separated by spaces: ");
String input = scanner.nextLine();
// Split input and convert to array of numbers
String[] inputNumbers = input.split(" ");
double sum = 0;
int count = inputNumbers.length;
for (String number : inputNumbers) {
sum += Double.parseDouble(number);
}
// Calculate and display the average
double average = sum / count;
System.out.printf("The average is: %.2f\n", average);
} catch (NumberFormatException e) {
System.out.println("Invalid input. Please enter numeric values only.");
} catch (ArithmeticException e) {
System.out.println("No numbers provided. Please enter at least one number.");
}
}
}
// Prompt the user for input
let input = prompt("Enter a list of numbers separated by spaces:");
// Convert input into an array of numbers
let numbers = input.split(" ").map(Number);
// Calculate the average
let sum = numbers.reduce((acc, num) => acc + num, 0);
let average = sum / numbers.length;
// Display the result
console.log(`The average is: ${average.toFixed(2)}`);
// Prompt the user for input
let input = prompt("Enter a list of numbers separated by spaces:");
try {
// Convert input into an array of numbers
let numbers = input.split(" ").map(num => {
if (isNaN(num)) {
throw new Error("Invalid input");
}
return parseFloat(num);
});
// Calculate the average
let sum = numbers.reduce((acc, num) => acc + num, 0);
let average = sum / numbers.length;
// Display the result
console.log(`The average is: ${average.toFixed(2)}`);
} catch (error) {
console.log("Error: Please enter valid numeric values.");
}