I'm new to Python and I have this problem:
I need to program a Python function that gives me back the sum of a list of numbers using a for loop.
I just know the following:
sum = 0
for x in [1,2,3,4,5]:
sum = sum + x
print[sum]
divibisan
10.7k11 gold badges39 silver badges57 bronze badges
asked Apr 26, 2014 at 10:35
3
I think what you mean is how to encapsulate that for general use, e.g. in a function:
def sum_list[l]:
sum = 0
for x in l:
sum += x
return sum
Now you can apply this to any list. Examples:
l = [1, 2, 3, 4, 5]
sum_list[l]
l = list[map[int, input["Enter numbers separated by spaces: "].split[]]]
sum_list[l]
But note that sum
is already built in!
answered Apr 26, 2014 at 10:42
jonrsharpejonrsharpe
110k25 gold badges215 silver badges397 bronze badges
0
l = [1,2,3,4,5]
sum = 0
for x in l:
sum = sum + x
And you can change l for any list you want.
answered Apr 26, 2014 at 10:38
zbszbs
6714 silver badges16 bronze badges
0
x=[1,2,3,4,5]
sum=0
for s in range[0,len[x]]:
sum=sum+x[s]
print sum
answered Apr 26, 2014 at 10:52
3
Sum in a for loop in Python #
To sum in a for loop in Python:
- Declare a new variable and set it to
0
. - Use a
for
loop to iterate over a sequence of numbers. - Reassign the variable to its value plus the current number.
Copied!
my_list = [2, 4, 6, 8] # ✅ sum using a for loop total = 0 for num in my_list: total += num print[total] # 👉️ 20 # ---------------------- # ✅ sum numbers in range using a for loop total_2 = 0 for num in range[1, 5]: total_2 += num print[total_2] # 👉️ 10 print[list[range[1, 5]]] # 👉️ [1, 2, 3, 4] # ---------------------- # ✅ sum numbers taken from user input using a for loop # 👇️ 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_3 = 0 for num in my_list: total_3 += num print[total_3] # 👉️ 10
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
.
On each iteration, we use the +=
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.
Copied!
my_list = [2, 4, 6, 8] total = 0 for num in my_list: total = total + num print[total] # 👉️ 20
If you need to add the numbers in a certain range using
a for
loop, create the range with the range[]
class.
Copied!
total_2 = 0 for num in range[1, 5]: total_2 += num print[total_2] # 👉️ 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:
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.
Copied!
# 👇️ 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_3 = 0 for num in my_list: total_3 += num print[total_3] # 👉️ 10
The input function takes an optional prompt
argument and writes it to standard output without a trailing newline.
The input[]
function is guaranteed to return a string even if the user enters a number.
We ued 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:
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.
We used a whitespace separator in the example, but you use any other separator that suits your use case.
Here is an example that splits the user-provided string on each comma.
Copied!
# 👇️ 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_3 = 0 for num in my_list: total_3 += num print[total_3] # 👉️ 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.
Copied!
# 👇️ 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.