Calculate the Sum of Integers: Python Code Example
Calculate the Sum of Integers: Python Code Example
This article provides a Python solution for calculating the sum of a series of integers. The input consists of multiple test cases, each with a number 'N' followed by 'N' integers. The program calculates the sum of each set of integers and outputs the result.
Input Format
The input consists of multiple test cases. Each test case is formatted as follows:
- N: An integer representing the number of integers in the following set.
- N integers: A series of 'N' integers separated by spaces.
The input is terminated by a test case starting with '0'. This terminating case is not processed.
Output Format
For each test case, the program outputs a single line containing the sum of the 'N' integers.
Solution
The solution uses a while loop to process the input until a test case with '0' is encountered. Inside the loop, the program reads the integer 'N', then reads 'N' integers using a for loop, adding them to a sum variable. Finally, the program prints the sum and an empty line after each test case.
Here's the Python code:
while True:
n = int(input())
if n == 0:
break
nums = list(map(int, input().split()))
sum = 0
for num in nums:
sum += num
print(sum)
print() # print a blank line after each test case
Example
Input:
5 1 2 3 4 5
3 10 20 30
0
Output:
15
60
原文地址: https://www.cveoy.top/t/topic/oMqH 著作权归作者所有。请勿转载和采集!