-
-
Save cpatulea/7243808 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Question: "Python: | |
>>> LINE A | |
>>> LINE B | |
>>> LINE C | |
False | |
>>> LINE A; LINE B; LINE C | |
True | |
what are the lines? nothing stateful allowed & no __methods." | |
(https://twitter.com/akaptur/status/395252265117687808). | |
My answer: | |
The given example. It relies on the fact that if the three lines are written together, | |
then they become part of the body of the for loop, whereas separated the for loop only | |
has the single statement in it. This is used to have variable (x) set to either 0 or 2 | |
at the end of the loop. Since the print statement will be executed twice if it's inside | |
the loop (the loop body executes twice), Nothing gets printed if x is 1, which happens | |
during the first iteration when the lines are written together. | |
The "x = n or x-1" allows initializing x on the first iteration - because n is -1, it | |
will be assigned -1. On the second iteration, n == 0 == False, so the statement will | |
assign x-1 to x. | |
Executing in Ipython I get: | |
In [142]: for n in range(-1,1):x=n or x-1; | |
In [143]: x+=2; | |
In [144]: sys.stdout.write("" if x == 1 else ("False" if x == 0 else "True")) | |
False | |
In [145]: for n in range(-1,1):x=n or x-1;x+=2;sys.stdout.write("" if x == 1 else ("False" if x == 0 else "True")) | |
True | |
In [146]: | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
for n in range(-1,1):x=n or x-1;x+=2;sys.stdout.write("" if x == 1 else ("False" if x == 0 else "True")) | |
for n in range(-1,1):x=n or x-1; | |
x+=2; | |
sys.stdout.write("" if x == 1 else ("False" if x == 0 else "True")) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment