Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python for loop with or?

Recently I came across some obfuscated python code, and I was having no problem separating out the pieces and understanding the little fragments of code. However, I came across one statement I didn't understand:

v, x = 1500, 1000
C = range(v*x)
import struct
P = struct.pack
M, j = '<QIIHHHH', open('M.bmp','wb').write
for X in j('BM'+P(M,v*x*3+26,26,12,v,x,1,24)) or C:

In the last line of code, I don't understand how this for loop can work with an or sitting there. The code runs fine, but I have no idea what it's doing. I tried looking in the Python docs, but I didn't see anything. What does this code do?

like image 807
jackcogdill Avatar asked Dec 19 '22 19:12

jackcogdill


1 Answers

If the return of j() == False, it iterates over C instead

Take a look at it in steps:

First, it evaluates this:

j('BM'+P(M,v*x*3+26,26,12,v,x,1,24))

Should that be considered equal to False (empty list, None, 0, etc), then it evaluates this:

C

and passes that as the iterable to the for loop

It should be noted that the or is not part of for syntax. It's evaluated prior to being passed into the for syntax you're familiar with

like image 104
mhlester Avatar answered Dec 30 '22 22:12

mhlester