简体   繁体   中英

Python- using sum in for loop with an error

Why should I write this program like this(first way) :

sum = 0
for i in range(1, 10):
    if (i % 3 == 0) or (i % 5 == 0):
        sum = sum + i
print(sum)
         

Why cant I write like this?(second way) :

for i in range(1, 10):
    if (i % 3 == 0) or (i % 5 == 0):
    print(sum(i))

In second way I receive this error :

TypeError: 'int' object is not iterable

What does this error mean exactly? Where may I use sum function? Where not?

Must I make a list to use sum function?

Thanks a lot

As the doc says, the first argument to the builtin function sum() needs to be an iterable.

Lists and tuples are examples of iterables. An int is not an iterable.

Now, in your first approach, sum is a variable that you have introduced, and unfortunately it has the same name as the built-in function. This should, in general, be avoided (introducing user-defined names that conflict with names of standard functions or modules)

In your second approach, sum refers to the built-in function of that name, and it expects an iterable (eg, list or tuple) as its first argument, but your are passing i , which is an int object

When you wrote sum=0 you have overwritten the python function sum() . so when you write sum(1) you ask python to calculate 0(1) which is not possible since 0 is not iterable

In general, it is not advised to assign sum to a value

What could work is either of the following codes:

s=0
for i in range(1, 10):
   if (i % 3 == 0) or (i % 5 == 0):
       s+=1
       print(s)

or better if you want to use the sum function:

print(sum([i for i in range(10) if (i % 3 == 0) or (i % 5 == 0)]))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM