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