Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How does this code work? It gives me 24 as output

`

n = [2, 4, 6, 8]
res = 1
for x in n[1:3]:
  res *= x

print(res)

`

I don’t understand how this code works or what it does. I believed that it should multiply x (which is chosen randomly from 4, 6, or 8) by res, but it doesn’t do that.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I thought that the n[1:3] meant numbers 1 and 3 (4 and 8 in the data set respectively) but that multiplies to 32. I don’t know what the x is now.
Can anyone explain how it works?

>Solution :

The for x in n[1:3] uses the numbers between the 1st and the one before the 3rd one

In this case it will use the 4 (position 1) and the 6 (position before the 3rd)

In order to do from 4 to 8 you need to use n[1:4]

I think that you want to multiply only the 4 and the 8 tho, in that case that implementation of the for loop would not work for you

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading