Last updated: Apr 9, 2024
Reading timeยท5 min
for
loopTo sum in a for loop in Python:
0
.for
loop to iterate over a sequence of numbers.my_list = [2, 4, 6, 8] total = 0 for num in my_list: total += num print(total) # ๐๏ธ 20
We used a for loop to sum the numbers in a list.
The first step is to declare a new variable and initialize it to 0
.
+=
operator to reassign the variable to its current value plus the current number.The following 2 lines of code achieve the same result:
total += num
total = total + num
Here is an example that uses the longer reassignment syntax.
my_list = [2, 4, 6, 8] total = 0 for num in my_list: total = total + num print(total) # ๐๏ธ 20
for
loopIf you need to add the numbers in a certain range using a for
loop, create the
range with the range()
class.
total = 0 for num in range(1, 5): total += num print(total) # ๐๏ธ 10 print(list(range(1, 5))) # ๐๏ธ [1, 2, 3, 4]
The range class is commonly used for looping a
specific number of times in for
loops and takes the following parameters:
Name | Description |
---|---|
start | An integer representing the start of the range (defaults to 0 ) |
stop | Go up to, but not including the provided integer |
step | Range will consist of every N numbers from start to stop (defaults to 1 ) |
If you need to sum numbers taken from
user input in a for loop, use the input()
function.
# ๐๏ธ user enters 1 2 3 4 user_input = input('Enter space-separated numbers: ') my_list = list(map(int, user_input.split())) print(my_list) # ๐๏ธ [1, 2, 3, 4] total = 0 for num in my_list: total += num print(total) # ๐๏ธ 10
The input function takes an optional prompt
argument and writes it to standard output without a trailing newline.
input()
function is guaranteed to return a string even if the user enters a number.We used the str.split()
function to split the string on each space.
The str.split() method splits the string into a list of substrings using a delimiter.
The method takes the following 2 parameters:
Name | Description |
---|---|
separator | Split the string into substrings on each occurrence of the separator |
maxsplit | At most maxsplit splits are done (optional) |
If the separator is not found in the string, a list containing only 1 element is returned.
Here is an example that splits the user-provided string on each comma.
# ๐๏ธ user enters 1,2,3,4 user_input = input('Enter comma-separated numbers: ') my_list = list(map(int, user_input.split(','))) print(my_list) # ๐๏ธ [1, 2, 3, 4] total = 0 for num in my_list: total += num print(total) # ๐๏ธ 10
After splitting the string, we get a list of strings, so we used the map()
function to convert each string in the list to an integer.
# ๐๏ธ user enters 1,2,3,4 user_input = input('Enter comma-separated numbers:') # ๐๏ธ ['1', '2', '3', '4'] print(user_input.split(','))
The map() function takes a function and an iterable as arguments and calls the function with each item of the iterable.
The map()
function passes each string to the
int() class and converts it
to an integer.
To get the sum of N numbers using a while loop:
0
.1
.sum_of_numbers = 0 num = 5 while num > 0: # ๐๏ธ reassign sum to sum + num sum_of_numbers += num # ๐๏ธ reassign num to num - 1 num -= 1 print(sum_of_numbers) # ๐๏ธ 15 (5 + 4 + 3 + 2 + 1) print(num) # ๐๏ธ 0
The while
loop in the example iterates for as long as the num
variable
stores a value greater than 0
.
+=
operator to reassign the sum_of_numbers
variable to its current value plus num
.To move toward the base case, we also use the -=
operator to reassign the
num
variable to its value minus 1
.
The following 2 lines of code achieve the same result:
sum_of_numbers += num
sum_of_numbers = sum_of_numbers + num
Similarly, the -=
operator is also a shorthand:
num -= 1
num = num - 1
while
loop, otherwise you might end up with an infinite loop.A commonly used alternative is to use a while True
loop with a break
statement.
sum_of_numbers = 0 num = 5 while True: # ๐๏ธ reassign sum to sum + num sum_of_numbers += num # ๐๏ธ reassign num to num - 1 num -= 1 # ๐๏ธ if num is equal to or less than `0`, break out of the loop if num <= 0: break print(sum_of_numbers) # ๐๏ธ 15 (5 + 4 + 3 + 2 + 1) print(num) # ๐๏ธ 0
The while True
loop iterates until it is interrupted by a break
statement.
I've also written an article on how to sum all values in a dictionary or a list of dictionaries.
You can learn more about the related topics by checking out the following tutorials: