You may like also: Python Random Number Examples

Python sum function example

Sum all elements from 0 to 100 (note exclusiveness here upper border is 101). This example sum all variations of 0..1, 0..2, 0..100:

for i in range(102):
    res = sum(range(i))
    print(res)

result:

0 -> 0
100 -> 4950
101 -> 5050

Python sum range with loop 0 to x

For loop can be used to sum all elements from 0 to x:

suma = 0
for i in range (101):
   suma += i
print(suma)

result:

5050

Python sum range with loop x to y

For loop can be used to sum all elements from 0 to x:

min = 20
max = 30
suma=0

for i in range (min,max+1):
   suma += i

result:

275

Python sum all elements of list

To sum all elements of list we can use simple loop:

suma = 0
list = [1,2,54,6,8,4,3,2,34,5]
for i in list:
   suma += i
print(suma)

result:

119

Python work with elements of list

If we want to iterate over list and perform some actions we can. List all elements, add 6 to each and produce new list:

list = [1,2,54,6,8,4,3,2,34,5]
newList = []

for i in list:
    newList.append(i + 6)

print(newList)

result:

[7, 8, 60, 12, 14, 10, 9, 8, 40, 11]

Python product of all elements of list

If we want to iterate over list and perform some actions we can. List all elements, add 6 to each and produce new list:

prod = 1
list = [1,2,54,6,8,4,3,2,34,5]
for i in list:
    prod *= i
print (prod)

result:

21150720

Error TypeError: 'int' object is not callable

this error is result of using variable sum in your code prior calling the function:

sum = 0
for i in range(102):
    res = sum(range(i))

results in

    res = sum(range(i))
TypeError: 'int' object is not callable

Two options to solve it:

  • find and change the name of the veriable
  • delete the usage by
newSum = sum
del sum