0

Help!

What is the output of this code? def func(x): res = 0 for i in range(x): res += i return res print(func(4)) why is the answer 6 and what is ''i'' ? also what is res?

18th Sep 2017, 10:32 PM
Duma Cristian
Duma Cristian - avatar
5 Réponses
+ 3
Hint: Try this in CodePlayground: for n in range(5): print(n)
18th Sep 2017, 11:08 PM
Kirk Schafer
Kirk Schafer - avatar
+ 3
https://code.sololearn.com/cx8G1wJdkUu7/?ref=app If you check your code and this, you will see the difference, so in this way, your range is from 0 to limit-1 inclusive. In your code 0+1+2+3=6 in my code 0+1+2+3+4=10
19th Sep 2017, 12:12 AM
Daniel
Daniel - avatar
+ 3
the answer is 6 because you passed 4 to def func (x) : # in your source code . ### therefore x = 4 for i in range (4) : # # range (0,4) ## range ( start, end at but not include) # ## same as for ( i= 0 ; i < 4 ; i++ ) ################ def func (x) : res =0 for i in range (4): res += i ### res = res + i return i ################# when i= 0 res = 0 # 0 when i = 1 res = 0 + 1 # res = 1 when i = 2 res = 1 + 2 # res = 3 when i =3 res = 3 + 3 # res = 6 ###### at final loop res = 6
19th Sep 2017, 6:27 AM
Rick Zalman
+ 1
res is a variable =0 and the for loop takes a variable ( i ) every time the loop runs , it take something and assigns it to ( i ) so for example num = [1,2,3] for i in num : print ( i ) this code will print 1, 2 , 3
19th Sep 2017, 12:50 AM
jay
+ 1
and u don't have to name it ( i ) u can name it anything u want to but by convention it's usually named. i
19th Sep 2017, 12:51 AM
jay