2017-11-16 1 views
0

저는 Python을 처음 사용하기 때문에 아래 코드를 실행하려고합니다. 하지만 오류가 계속 발생합니다 :'int'객체가 반복 가능하지 않음 오류 : Python

int object not iterable.

배열의 sqaures 합계를 계산하고 싶습니다. 여기에 코드가 있습니다. 변수 product이 이미 정의되었으므로 걱정할 필요가 없습니다.

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

print (sumofsquares(product)) 
+1

1. 들여 쓰기를 수정하십시오. 2. '제품'이란 무엇입니까? – NPE

답변

1

가정 제품은 당신이 sqaures의 합계를 찾으려는 숫자를 포함하는 list, 당신은 list을 통해 반복하고 각 숫자의 제곱을 계산하고 result라는 목록에 추가 할 수 있습니다. 마침내 그 목록의 합계를 반환 할 수 있습니다. 코드에서

당신은 다음과 같이 할 수 ..

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 

희망이 도움이됩니다. !!

+0

고마워요. 완벽하게 잘 작동했습니다. 또한, 주어진 오류 뒤에있는 논리를 설명해 주시겠습니까? 그래서 나는 그것을 더 잘 이해할 수 있습니다. – Kaleembukhari

+0

도와 주셔서 감사합니다. 응답을 수락하고 upvote 경우. –

+1

또한,'result.append (sum ((x1) [i] ** 2))')를 수행 중이므로 오류가 발생합니다. 왜냐하면 목록 항목은'listname [index]'처럼 접근해야하기 때문입니다. 또한'sum' 함수는'list' 또는 하나 이상의 숫자에 적용되어야합니다. –

관련 문제