Computer Science, asked by formless, 4 months ago

A question from Python programming language:
sum=0
for i in range(12,2,-2):
sum+=i
print(sum)

Answer I know, it is 40 but idk how?
Kindly explain.

Answers

Answered by atrs7391
6

sum=0

#In this line you're declaring variable sum and initializing it's value 0

for i in range(12,2,-2):

#this is for loop in which variable i's value will iterate from 12 to 2 with -2 step

#that means at the first run it will be 12 then 2 will decrease in the second run and will become 10

#so the values will be 12, 10, 8, 6, 4

    sum+=i

   #now here sum's value will add with the value of i

   #i.e. sum = 12+ 10+ 8+ 6+ 4

  #at first run it will be 12 then 12+10 then 12+10+8 then 12+10+8+6 then     12+10+8+6+4 then  12+10+8+6+4.

print(sum)

#after running the and adding them the sum is 40 so it will print 40

Similar questions