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?
5 Réponses
+ 3
Hint: Try this in CodePlayground:
for n in range(5):
print(n)
+ 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
+ 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
+ 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
+ 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