+6

I don’t understand why the result is 6.

https://code.sololearn.com/c42Y1t2GRk9c/?ref=app Please help me,thank you.

6/16/2019 2:19:46 PM

Legend_Duck

9 Answers

New Answer

+7

for i in range(4): #0, 1, 2, 3 res += 0 #res = 0 + 0 = 0 res += 1 #res = 0 + 1 = 1 res += 2 #res = 1 + 2 = 3 res += 3 #res = 3 + 3 = 6

+9

First loop >>> i = 0 res += i >>> res = 0 Second loop >>> i = 1 res += i >>> res = 1 Third loop >>> i = 2 res += 2 >>> res = 3 Fourth loop >>> i = 3 res += 3 >>> res = 6 Finally the loop ends and value of res variable is 6.

+8

Legend_Duck Why you don't understand the result, didn't you coded it ? Anyways i in for loop varies from 0 to 3 0. 1, 2, 3 add this you have your answer

+6

First, put a colon at the end if line 3 so it reads like this. for i in range(x): Second, the explanation. Line 7 is where you are passing the value of 4 to a function named “func”. Lines 1 through 5 is the function. • Line 1 declares the name if the function while telling it a variable is getting passed in it. • Line 2 sets a variable “res” to 0. • Line 3 sets up a “for loop” to count from the value of “i” (which is zero) up to the number x (which is 4, set in line 7). Counting starts at 0 and goes up to 3. It does four loops as specified when you pass a 4 as x in line 7. • Line 4 does the math. • On 1st pass through loop “res” is equal to 0 and i equals 0. So res = res + 0. Res = 0. • On 2nd pass through loop “res” is equal to 0 and i equals 1. So res = res + 1. Res = 1. • On 3rd pass through loop “res” is equal to 1 and i equals 2. So res = res + 2. Res = 3. • On 4th pass through loop “res” is equal to 3 and i equals 3. So res = res + 3. Res = 6. • Line 5 returns the value of “res” as the result of the function. Helpful? 🇺🇸

+4

You can see the result step by step. It is sum of each "i" in each step:https://code.sololearn.com/cxERzgM5t6px/?ref=app

+4

Thanks for helping me.😃👍

+3

because the code is adding i to res like 0+1+2+3 which is equal to 6

+3

res = 0 res+=i(0) res+=i(1) res+=i(2) res+=i(3) 0+1+2+3 = 6 res=6

+2