Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/330.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 3.x范围函数计算和Einrü;钟_Python_Math - Fatal编程技术网

python 3.x范围函数计算和Einrü;钟

python 3.x范围函数计算和Einrü;钟,python,math,Python,Math,Python代码: b=0 for x in range (4): a=b+x print (a) 为什么结果是3而不是6,即0+1+2+3?这是因为您将a设置为b,即0+x,每次调用它时,您都会覆盖a的值,我已经重写了您的代码,希望它能有所帮助 b=0 #Sets the value of b to 0 for x in range(4): #this will run the code below 4 times b=b+x #makes b equal to itse

Python代码:

b=0
for x in range (4): 
    a=b+x 
print (a)

为什么结果是3而不是6,即0+1+2+3?

这是因为您将a设置为b,即0+x,每次调用它时,您都会覆盖a的值,我已经重写了您的代码,希望它能有所帮助

b=0 #Sets the value of b to 0
for x in range(4): #this will run the code below 4 times
    b=b+x #makes b equal to itself, plus the vaue of x.

print(b) #outputs the value of b

主要问题是,您总是更新a而不是求和其值,并且不需要
b=0

a = 0
for x in range (4): 
    a+=x 
print (a)

因为您每次都在重新指定
a
的值

您的代码相当于以下代码:

b=0
x=0 
a=b+x # a = 0 +0
x=1
a=b+x # a = 0 + 1
x=2
a=b+x #a = 0 + 2
x=3
a=b+x #a = 0 + 3
print (a) # 3 is the final value of a
我想你想做的是:

a=0
for x in range(4):
    a += x # or equivalently a = a+x
print(a)
我不明白您为什么也使用变量
b

请注意,还有一个更紧凑的解决方案:

a = sum(range(4))

因为
b
将永远是
0
。整数是不可变的。此外,由于您的缩进不正确,还不清楚
print
实际发生在何处。为什么不使用内置的
sum
:-
print(sum(范围(4))