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?

18th May 2020, 4:11 AM
Zach Janzen
10 Answers
+ 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
18th May 2020, 5:07 AM
Utkarsh Sharma
Utkarsh Sharma - avatar
+ 1
print(sum(10)) It means that it it prints the sum of the numbers from 0 to 9.
18th May 2020, 4:18 AM
James Clark I. Vinarao
James Clark I. Vinarao - avatar
+ 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
19th May 2020, 3:45 AM
Ahmed Muhammed
Ahmed Muhammed - avatar
0
This code print like this: 0+1+2+3+4+5+6+7+8+9 And the final result is 45.
18th May 2020, 4:23 AM
ROHIT KUMAR
ROHIT KUMAR - avatar
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
18th May 2020, 4:28 AM
Zach Janzen
0
Yes 👍
18th May 2020, 4:28 AM
ROHIT KUMAR
ROHIT KUMAR - avatar
0
thanks dude
18th May 2020, 5:56 AM
Zach Janzen
0
This question is finally making sense.
19th May 2020, 3:54 AM
Zach Janzen
0
n = [2, 4, 6, 8] res = 1 for x in n[1:3]: res *= x print(res) ans: 24
7th Dec 2022, 9:59 AM
Yashashwini Reddy M S
0
12
21st Jan 2023, 8:30 AM
Wondifraw Seifu
Wondifraw Seifu - avatar