The average of the sequence. Determine the average 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 calculation of the average.
|
total_sum = 0 count = 0 while True: num = int(input()) if num == 0: break total_sum += num count += 1 if count > 0: average = total_sum / count print(average) |
Explanation of the Code
- Initialize Sum and Count:
- Initialize two variables,
total_sum
and count
, to 0. These will keep track of the sum of the integers and the count of the integers in the sequence, respectively.
- Reading Input and Summing:
while True:
num = int(input())
if num == 0:
break
total_sum += num
count += 1
- 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
and increment count
by 1.
- Calculating and Printing the Average:
if count > 0:
average = total_sum / count
print(average)
- If
count
is greater than 0, calculate the average by dividing total_sum
by count
.
- Print the calculated average.