what is the use-case of Python3 only `if` and `break` in `for`?
Question:
I am learning python but
https://github.com/python-pillow/Pillow/blob/main/src/PIL/JpegImagePlugin.py#L435-L437
https://github.com/python-pillow/Pillow/blob/31669013d420c2a532f5be6c5631827fe36e6f70/src/PIL/JpegImagePlugin.py#L435-L437
I am watching the code of PIL of python then I can not understand here.
for s in [8, 4, 2, 1]:
if scale >= s:
break
Is the PIL library wrong?
I did:
watch the code and think about it.
Answers:
The variable s
will remain in scope after the loop, and contain the first value of that list which is smaller than or equal to scale
.
In other words, this code "rounds down" scale
to one of these four specific numbers.
I might have done s = next(s for s in [8, 4, 2, 1] if scale >= s)
to make that more apparent, but this loop is probably slightly more performant.
I am learning python but
https://github.com/python-pillow/Pillow/blob/main/src/PIL/JpegImagePlugin.py#L435-L437
https://github.com/python-pillow/Pillow/blob/31669013d420c2a532f5be6c5631827fe36e6f70/src/PIL/JpegImagePlugin.py#L435-L437
I am watching the code of PIL of python then I can not understand here.
for s in [8, 4, 2, 1]:
if scale >= s:
break
Is the PIL library wrong?
I did:
watch the code and think about it.
The variable s
will remain in scope after the loop, and contain the first value of that list which is smaller than or equal to scale
.
In other words, this code "rounds down" scale
to one of these four specific numbers.
I might have done s = next(s for s in [8, 4, 2, 1] if scale >= s)
to make that more apparent, but this loop is probably slightly more performant.