0
Python test question
def sum(x): res = 0 for i in range(x): res += i return res print(sum(10)) Could someone please explain how this chunk of code works?
10 Respostas
+ 3
Zach Janzen
def sum(x):
res = 0
for i in range(x):
res+= i
return res
we have defined a function here named sum which take a number x
print( sum(10) )
Thus statement will print the result after we give x=10 in sum
res = 0
for i in range(10):
res+= i
return res
Now the for loop will be executed and it will become
res = res + 0
res = res + 1
res = res + 2
.
.
.
res = res + 9
after for loop is over
return res
will return the value of res
which the print( sum(10)) will print
And hence 45 is answer
+ 1
print(sum(10))
It means that it it prints the sum of the numbers from 0 to 9.
+ 1
res=0
res=0+1=1
res=1+2=3
res=3+3=6
res=6+4=10
res=10+5=15
res=15+6=21
res=21+7=28
res=28+8=36
res=36+9=45
0
This code print like this:
0+1+2+3+4+5+6+7+8+9
And the final result is 45.
0
i understand what it does. i guess my question was how does it work like what each line of code does and how it is able to print out the sum of nukbers from 0 to 9
0
Yes 👍
0
thanks dude
0
This question is finally making sense.
0
n = [2, 4, 6, 8]
res = 1
for x in n[1:3]:
res *= x
print(res)
ans: 24
0
12