Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/search/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 求和数的平方_Python - Fatal编程技术网

Python 求和数的平方

Python 求和数的平方,python,Python,这段代码将所有自然数相加到10,然后在Python中取该和的平方。我哪里出错了 def square_of_sum(): sum = 0 for x in xrange(11): if x <= 10: x + sum = sum x += 1 else: print sum*sum break 啊,我看你喜欢: 解决方案 我想这就是你所说的代

这段代码将所有自然数相加到10,然后在Python中取该和的平方。我哪里出错了

def square_of_sum():
    sum = 0
    for x in xrange(11):
        if x <= 10:
            x + sum = sum
            x += 1
        else: 
            print sum*sum
            break
啊,我看你喜欢:

解决方案 我想这就是你所说的代码:

def square_of_sum():
  sum_ = 0
  for x in xrange(1, 11):
    sum_ += x
  return sum_ ** 2
def square_of_sum():
    s = 0
    for x in xrange(11):
        s += x
    print s**2
要更习惯地重写此内容,请使用生成器理解和内置:

def square_of_sum():
  return sum(range(11)) ** 2
如果您注重性能,您可以通过注意查找算术级数的和来消除循环:

def square_of_sum(x):
   print (x * (x + 1) / 2) ** 2
修复 至于为什么你的代码不起作用,有很多原因

首先,我认为您对Python中for循环的工作方式感到困惑。基本上,它只是在数组上循环。当x大于10时,您不必检查和中断,也不必增加它。阅读有关如何使用for循环的详细信息。要查看何时使用它的示例,请参阅

其次,变量赋值是用左边的变量和右边要求值的表达式来完成的。因此,为了简洁起见,x+sum=sum实际上应该是sum=sum+x或sum+=x

第三,sum是一个内置函数。您可能不想也不应该对其进行过度阴影处理,所以请将sum变量重命名为其他变量

最后,sum*sum相当于将其提高到2的幂,您可以使用**运算符来实现这一点:sum**2


希望这有助于您理解。

要修复代码中的错误:

def square_of_sum():
  sum_ = 0
  for x in xrange(1, 11):
    sum_ += x
  return sum_ ** 2
def square_of_sum():
    s = 0
    for x in xrange(11):
        s += x
    print s**2
或者,更习惯地说

def square_of_sum(n):
    print sum(range(n + 1)) ** 2
或者,为了消除循环:

def square_of_sum(n):
    print (n * (n + 1) / 2) ** 2

有几个问题。首先,sum是一个内置函数,所以您可能不想命名任何这样的函数,所以请使用一个名为total的变量

其次,变量赋值是用左边的变量和右边的表达式完成的,因此x+total=total应该是total=x+total,或者为了简洁起见,total+=x

第三,因为x==11的情况基本上只是一个返回情况,所以它应该在循环之外

最后,total*total等于total**2;这是更容易使用的东西,如

def square_of_sum():
    total = 0
    for x in xrange(11):
        if x <= 10:
            total += x
            x += 1
    print total ** 2

你得到了什么样的产出,你期望得到什么样的产出?