Table of Contents

Find the Sum of Positive Numbers | Pictoblox

Example Description
Python program to find the sum of all the positive numbers entered by the user till the user enters a negative number.

Introduction:

In this Python program, we will find the sum of all positive numbers entered by the user until the user enters a negative number. We will use a while loop to continuously input numbers from the user and add them to the sum1 variable until a negative number is entered.

Code:

#Find the sum of all the positive numbers entered by the user till the user enters a negative number. 
entry = 0
sum1 = 0
print("Enter numbers to find their sum, negative number ends the loop:")
while True: 
#int() typecasts string to integer 
 entry = int(input())
 if (entry < 0):
  break
 sum1 += entry
print("Sum =", sum1)

Logic:

  1. Initialize the variables ‘entry’ and ‘sum1’ to 0.
  2. Print a message asking the user to enter numbers to find their sum, and inform them that a negative number will end the loop.
  3. Start an infinite loop using ‘while True’.
  4. Use the ‘int()’ function to convert the user’s input into an integer and assign it to the variable ‘entry’.
  5. Check if ‘entry’ is less than 0. If it is, break out of the loop.
  6. Add the value of ‘entry’ to the current value of ‘sum1’.
  7. Repeat steps 4-6 until a negative number is entered.
  8. Print the final sum using the ‘print()’ function.

Output:

Sum = (sum of positive numbers entered by the user)

> Enter numbers to find their sum, negative number ends the loop:1

2

3

4

5

6

7

8

9

0

-1

>> Sum = 45