0
Python For Loop
What is the output of this code? def func(x): res = 0 for i in range(x): res += i return res print(func(4))
7 Answers
+ 6
You have passed 4 to func() and then you have made res = 0. For loop when runs it starts from 0 and checks whether it is below 4. Condition is yes so res = res + 0 since i is 0. Similarly in the next step i becomes 1 and is below 4 so res = 0+1. This loop goes on till i is 3 because 3 is in range of 4. And your res is updated as res = 0+1+2+3 which is 6. So the output is 6 and always remember the in range checks for n-1 numbers so it will check only 4-1 = 3.
+ 3
adhamZ18 yes
0
i dont even understand the code.
i tried it myself yes and i don't get it :(
0
i mean res+= i is res=res+i
but what is the value of i?
im missing something
0
so the value of i increases each time the loop repeats itself?
0
the default value of i variable is 0.
but you can use range to assign it the value you want. like:
for i in range(10,25)
0
Yes, the value of i is increased by 1 each time you run through the loop.
When you called func(4) in the print statement you asked range(4) to go through the loop. With each loop you define i as first 0, then 1, then 2, then 3. At that point the loop stops since 3 is the last number in range(4). With each loop you also added i to the last res. So res becomes 0+0, then 0+1, then 1+2, then 3+3.
You could think of the i in the for loop as saying:
Round 1: for this round i = 0
Round 2: for this round i = 1
Round 3: for this round i = 2
Round 4: for this round i = 3