简体   繁体   中英

'int' object not iterable error: Python

I am new to python, and I am trying to run the code given below. But it keeps throwing an error:

int object not iterable.

I want to calculate the sum of sqaures in an array. Here is the code. The variable product is already defined, so that is not the worrisome part.

def sumofsquares(x1):
    result=[]
    for i in range (len(x1)):
        result.append(sum((x1)[i]**2))
    return result

print (sumofsquares(product))

Assuming product is a list containing the numbers you want to find the sum of sqaures, you can iterate through the list and calculate squares of each number and add it to a list called result . At last you can return the sum of that list.

In codes you can do like this..

def sumofsquares(x1):
    result = [] # list to store squares of each number

    for i in range(len(x1)): # iterating through the list
        result.append(x1[i] ** 2) # squaring each number and appending to the list

    return (sum(result)) # returning the sum of the list

product = [1, 2, 3] # declaring the array to find sum of sqaure
print (sumofsquares(product)) # calling the function and displaying the return value

# Output
14

Hope this helps.!!

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