The sum of the sequence. Determine the sum of all elements in a sequence of non-negative integers, where the sequence ends with the number 0. Do not include the 0 in the sum.
|
total_sum = 0 while True: num = int(input()) if num == 0: break total_sum += num print(total_sum) |
Explanation of the Code
- Initialize Sum:
- Initialize a variable
total_sum
to 0 to keep track of the sum of the integers in the sequence.
- Reading Input and Summing:
while True:
num = int(input())
if num == 0:
break
total_sum += num
- Use a
while True
loop to continuously read input.
- Convert the input to an integer using
int()
.
- If the integer is 0, break the loop.
- If the integer is not 0, add it to
total_sum
.
- Printing the Sum of the Sequence:
- Print the value of
total_sum
after exiting the loop.