SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Tony Gaddis
Chapter:
Repetition Structures
Exercise:
Programming Exercises
Question:8 | ISBN:9780132576376 | Edition: 2

Question

Sum of Numbers
Write a program with a loop that asks the user to enter a series of positive numbers. The user should enter a negative number to signal the end of the series. After all the positive numbers have been entered, the program should display their sum.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Sum of Numbers program code:

#initialized variable
total = 0
#a while loop that asks the user to enter a 
#series of positive numbers. The user should
#enter a negative number to signal the end 
#of the series. 
while True:
    number = float(input("Enter a positive number (enter a negative number to end): "))
    if number < 0:
        break
    total += number
#Display the sum of positive numbers 
print("The sum of the positive numbers entered is:", total)

Executed Output:

Enter a positive number (enter a negative number to end): 5
Enter a positive number (enter a negative number to end): 10
Enter a positive number (enter a negative number to end): 20
Enter a positive number (enter a negative number to end): 30
Enter a positive number (enter a negative number to end): 40
Enter a positive number (enter a negative number to end): 95
Enter a positive number (enter a negative number to end): -5
The sum of the positive numbers entered is: 200.0

 

0 0

Discussions

Post the discussion to improve the above solution.