Exercise
Numerous Numbers And Their Sum
Objective
Develop a Python program that prompts the user for several numbers (until they enter "end") and displays their sum. When the execution is about to end, it must display all the numbers entered and the sum again, as follows:
Enter a number: 5
Sum = 5
Enter a number: 3
Sum = 8
Enter a number: end
The numbers are: 5 3
The sum is: 8
Example Python Exercise
Show Python Code
# Program developed by: Programmer 1, Programmer 2
# Initialize an empty list to store the numbers
numbers = []
total_sum = 0
# Start prompting the user for numbers
while True:
number = input("Enter a number: ")
if number.lower() == "end":
break
# Try to convert the input to a number
try:
number = float(number) # Convert the input to a float
numbers.append(number) # Add the number to the list
total_sum += number # Add the number to the sum
print(f"Sum = {total_sum}") # Display the current sum
except ValueError:
print("Please enter a valid number or 'end' to stop.") # Handle invalid input
# Display all the numbers entered and the final sum
print("The numbers are:", ' '.join(map(str, numbers)))
print(f"The sum is: {total_sum}")
Output
Enter a number: 5
Sum = 5
Enter a number: 3
Sum = 8
Enter a number: 7
Sum = 15
Enter a number: -2
Sum = 13
Enter a number: 4.5
Sum = 17.5
Enter a number: end
The numbers are: 5.0 3.0 7.0 -2.0 4.5
The sum is: 17.5
Share this Python Exercise