Exercise
Calculating An Unlimited Sum
Objective
Develop a Python program to calculate an unlimited sum by continuously adding numbers provided by the user. The program should allow the user to input numbers indefinitely, and keep a running total. The user should be able to stop the input process at any time (e.g., by entering 'exit' or a special keyword), and the program should display the final sum.
Example Python Exercise
Show Python Code
def calculate_sum():
"""Continuously adds numbers provided by the user and keeps a running total."""
total = 0 # Initialize the running total to 0
print("Enter numbers to add to the sum. Type 'exit' to stop and display the final sum.")
while True:
user_input = input("Enter a number: ").strip() # Take user input and remove extra spaces
if user_input.lower() == 'exit':
# If the user types 'exit', stop the loop and display the final sum
print(f"The final sum is: {total}")
break
try:
# Try to convert the input to a float and add it to the total
number = float(user_input)
total += number
except ValueError:
# If the input is not a valid number, print an error message
print("Invalid input. Please enter a valid number or type 'exit' to stop.")
def main():
"""Main function to run the sum calculation program."""
calculate_sum()
# Run the program
if __name__ == "__main__":
main()
Output
Enter numbers to add to the sum. Type 'exit' to stop and display the final sum.
Enter a number: 10
Enter a number: 25.5
Enter a number: -5
Enter a number: exit
The final sum is: 30.5
Share this Python Exercise