I want to sum the elements of a list that are placed only on an even number position.
This is what I have, but it doesn't seam to work.
code=input("SVP entrez le code :")
r=range(0,11,2)
sum=(sum(i) for i in r)
print(sum)
I want to sum the elements of a list that are placed only on an even number position.
This is what I have, but it doesn't seam to work.
code=input("SVP entrez le code :")
r=range(0,11,2)
sum=(sum(i) for i in r)
print(sum)
I think you are getting a error like below,
TypeError: 'int' object is not iterable
this is because you are trying to sum each variable (int) in the range,
But the syntax of sum() is:
sum(iterable, start)
If you pass the range directly to sum method, it will give you the correct output, also try not to use sum as name for variable, below change should get the answer you are looking for, good luck
code=input("SVP entrez le code :")
r=range(0,11,2)
my_sum=sum(r)
print(my_sum)
more information on the sum can be found here https://www.programiz.com/python-programming/methods/built-in/sum
Here you go, I'm assuming you are starting at 0 if not just use [2::2]
code = int(input("Enter code: "))
numbers = []
for i in (str(code)):
numbers.append(int(i))
total = sum(numbers[::2])
print(total)
(xenial)vash@localhost:~/python$ python3.7 code.py Enter code: 123456 9