Can someone please help me understand what this code is doing step-by-step?
sum = 0
for i in range (1, 11):
if (i % 2 == 0):
for j in range(10 - i):
if (i - j > 0):
sum = sum + (i - j)
print (sum)
Can someone please help me understand what this code is doing step-by-step?
sum = 0
for i in range (1, 11):
if (i % 2 == 0):
for j in range(10 - i):
if (i - j > 0):
sum = sum + (i - j)
print (sum)
Hello!
I try to comprehend in some steps. Letâ€™s begin!
Calculating i - j for a), b), c) and d). Take only positiv values into account and sum up them.
case a): i = 2
x1 = 2 - 0 = 2 > 0
x2 = 2 - 1 = 1 > 0
sum1 = x1 + x2 = 2 + 1 = 3
case b): i = 4
x1 = 4 - 0 = 4 > 0
x2 = 4 - 1 = 3 > 0
x3 = 4 - 2 = 2 > 0
x4 = 4 - 3 = 1 > 0
sum2 = x1 + x2 + x3 + x4 = 4 + 3 + 2 + 1 =10
case c): i = 6
x1 = 6 - 0 = 6 > 0
x2 = 6 - 1 = 5 > 0
x3 = 6 - 2 = 4 > 0
x4 = 6 - 3 = 3 > 0
sum3 = x1 + x2 + x3 + x4 = 6 + 5 + 4 +3 = 18
case d): i = 8
x1 = 8 - 0 = 8 > 0
x2 = 8 - 1 = 7 > 0
sum4 = x1 + x2 = 8 + 7 = 15
The result of you your code will be:
sum = sum1 + sum 2 + sum3 + sum4 = 3 + 10 + 18 + 15 = 46
I hope I have done no mistake!