Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple python and need explanation

Tags:

python-3.x

m = 0
for x in range (4,6):
   for y in range (2,4):
      m = m + x + y
print (m)

ANSWER: 28

not sure how this is? Excluding the last number in the range, I thought it should be 14. I add it up on paper and cannot understand what I am doing wrong.

like image 243
todd2323 Avatar asked Feb 25 '26 18:02

todd2323


1 Answers

That loop is equivalent to:

m = 4+2 + 4+3 + 5+2 + 5+3

And, that sum is 28.

(In the outer loop, x takes on the values 4 and 5. In the inner loop, y takes on values 2 and 3.)

like image 52
John1024 Avatar answered Feb 27 '26 08:02

John1024



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!