How to Sum Numbers in For and While Loops in Python
Summing numbers in a loop is a fundamental programming task.
This guide explores various techniques for calculating sums using both for
and while
loops in Python, covering different scenarios like summing items from a list, numbers in a range, and dynamically collecting values from user input.
How to Sum Numbers in a List with a for
Loop
To sum numbers stored in a list, use a for
loop to iterate through the list and accumulate the sum:
my_list = [2, 4, 6, 8]
total = 0
for num in my_list:
total += num
print(total) # Output: 20
- Initialize a variable to store the sum (e.g.,
total = 0
). - Iterate over each number in the list and add it to the
total
. - After the loop finishes you get the sum of all items in the list.
How to Sum Numbers in a Range with a for
Loop
To sum numbers in a specific range, use the range()
function with a for
loop:
total = 0
for num in range(1, 5):
total += num
print(total) # Output: 10
print(list(range(1, 5))) # Output: [1, 2, 3, 4]
range(1, 5)
generates numbers from1
up to (but not including)5
.- Inside the loop we add the current number generated by range to the total sum, so in this case, we are summing all of the numbers starting from
1
until4
.
How to Sum Numbers from User Input with a for
Loop
To sum numbers entered by the user, combine input()
, split()
, and map()
functions:
user_input = input('Enter space-separated numbers: ')
my_list = list(map(int, user_input.split()))
total = 0
for num in my_list:
total += num
print(total)
# Example
# Input: 1 2 3 4
# Output: 10
- The code prompts the user to input space-separated numbers using
input()
. - Then the
split()
method splits the string into multiple string numbers separated by spaces. - The
map()
function andint()
method are then used to transform each string to a number, and construct a new list of integers with these numbers. - Finally, a for loop is used to sum the numbers as we did in the first example.
- Use try/except statements for more robust code that also handles invalid input, like what would happen if the user types
a
instead of1
.
How to Sum N Numbers with a while
Loop
You can also use a while
loop to sum a fixed number of integers.
sum_of_numbers = 0
num = 5
while num > 0:
sum_of_numbers += num
num -= 1
print(sum_of_numbers) # Output: 15 (5 + 4 + 3 + 2 + 1)
- The
while
loop will continue as long asnum > 0
to add numbers to the sum. num -= 1
is then used to decrement the number by one to reach the base case, where thewhile
condition will beFalse
.