[英]I am having a problem with understanding this python code
I want to learn Python and I took a test. 我想学习Python并参加了测试。 I the test I came across this code and I needed to get it's output. 在测试中,我遇到了这段代码,我需要获取它的输出。
I put the correct answer which was 6, but I didn't understand the code, I just put it in an online python compiler! 我输入的正确答案是6,但我不理解代码,只是将其放在在线python编译器中!
Why does this code output a 6
? 为什么此代码输出6
?
def func(x):
res = 0
for i in range(x):
res += i
return res
print(func(4))
I thing this will solve your problem buddy 我认为这将解决您的问题伙伴
def func(x):
res = 0
for i in range(x):
print "x",i
print "res",res
res += i
print "res out", res
return res
print(func(4))
result: 结果:
x 0
res 0
res out 0
x 1
res 0
res out 1
x 2
res 1
res out 3
x 3
res 3
res out 6
6
you're passing number 4
as variable x
into the function and printing the result in the end. 您将数字4
作为变量x
传递到函数中,并最终输出结果。
in the for loop, i
is a temporary variable representing each number in range 0
to 4
. 在for循环中, i
是一个临时变量,表示范围0
到4
每个数字。
so the steps in the code look like this 所以代码中的步骤如下所示
for 0 in range 0 to 4
add 0
to variable res
= 0 + 0 = 0
将0
添加到variable res
= 0 + 0 = 0
now res = 0 现在res = 0
next step/loop for 1
in range 0 to 4
下一步骤/循环,范围为0 to 4
为1
add 1
to variable res
= 0 + 1 = 1
将1
加到variable res
= 0 + 1 = 1
now res = 1
现在res = 1
next step/loop for 2
in range 0 to 4
下一步骤/回路2
在范围0 to 4
add 2
to variable res
= 1 + 2 = 3
将2
加到variable res
= 1 + 2 = 3
now res = 3
现在res = 3
next step/loop for 3
in range 0 to 4
下一步骤/回路3
在范围0 to 4
add 3
to variable res
= 3 + 3 = 6
将3
加到variable res
= 3 + 3 = 6
now res = 6
现在res = 6
and the loop is done, giving you the result 6 循环完成,为您提供结果6
You assign the value of i to the res and then res value is added to the value of i and your output is assign to the value of res that is when x=3, res become 3 and added with the value 3 is equal to 6 boom 您将i的值分配给res,然后将res值添加到i的值,然后将输出分配给res的值,即x = 3,res变为3并加值3等于6繁荣
def is used to define function and range means from start to the end point you want so in your case you passed 4 as variable x into your function that means your loop start with the value of 0 and end when value is 4. def用于定义函数,范围的意思是从起点到所需的终点,因此在这种情况下,您将4作为变量x传递到函数中,这意味着循环以0的值开始,而当值为4时结束。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.