Sum of N numbers. Given an integer N followed by N integers, read these integers and print their sum. The first line of input contains the integer N, which indicates how many integers will follow. Each of the next N lines contains one integer. Calculate and print the sum of these N integers.
|
N = int(input()) total_sum = 0 for _ in range(N): total_sum += int(input()) print(total_sum) |
- Reading the Number of Integers:
- The
input()
function reads the first line of input.
- The
int()
function converts this input to an integer and stores it in the variable N
.
- Initialize the Sum:
- A variable
total_sum
is initialized to 0. This will be used to store the sum of the N integers.
- Reading and Adding Integers:
for _ in range(N):
total_sum += int(input())
- A
for
loop runs N
times, as indicated by range(N)
.
- Each iteration reads a number from the user using
input()
, converts it to an integer with int()
, and adds it to total_sum
.
- Printing the Total Sum:
- Finally, the
print()
function outputs the value of total_sum
.