这个为啥报错
def square_of_sum(L):
for i in L:
return sum(i*i)
print square_of_sum([1, 2, 3, 4, 5])
print square_of_sum([-5, 0, 5, 15, 25])
def square_of_sum(L):
for i in L:
return sum(i*i)
print square_of_sum([1, 2, 3, 4, 5])
print square_of_sum([-5, 0, 5, 15, 25])
2018-11-13
涉及到求和,求平均数,最好先赋予整数或者浮点数,然后遍历一个变量(for i in L:),这是一个求和的函数,所以应该写(sum = sum + x*x),sum函数=sum(按照一开始赋予的整数或者浮点数) + x*x(循环方式),然后返回求和 (return sum)——这个是sum= sum + x*x最左边的sum,=号后面的sum是最开始那个赋值的sum,这两个意义不同,我写两段代码,你看一下
1,
def square_of_sum(L):
sum = 0
for x in L:
x = x*x #这种格式必须把x的循环方式写在上面,不能写在sum=sum + x,下面,不然逻辑就错了
sum = sum + x
return sum
2,
def square_of_sum(L):
sum = 0
for x in L:
sum = sum + x*x #这种格式也好理解,sum(求和函数)=sum(一开始的赋值) + x*x(循环方式)
return sum
举报