_='_=%r;print (_%%_) ';print (_%_)
(Edit: I have recieved your input and fixed the code, thanks for the correction.)
This is the shortest quine you can write in Python (I'm told). A quine being code that returns itself.
Can someone explain this line of code to me as if I know nothing about Python? I use Python 3.x by the way.
What I'm looking for is a character-by-character explanation of what's going on.
Thanks.
As pointed out in the comments, the correct quine is _='_=%r;print (_%%_) ';print (_%_)
. Using this, let's begin:
The ;
executes two commands in a line, so the following:
_='_=%r;print (_%%_) ';print (_%_)
is equivalent to:
_='_=%r;print (_%%_) '
print (_%_)
In the first line, _
is a valid variable name which is assigned the string '_=%r;print (_%%_) '
Using python's string formatting, we can inject variable into strings in a printf fashion:
>>> name = 'GNU'
>>> print('%s is Not Unix'%name)
GNU is Not Unix
>>> print('%r is Not Unix'%name)
'GNU' is Not Unix
%s
uses a string, %r
uses any object and converts the object to a representation through the repr()
function.
Now imagine you want to print a %
as well; a string such as GNU is Not Unix %
. If you try the following,
>>> print('%s is Not Unix %'%name)
You will end up with a ValueError
, so you would have to escape the %
with another %
:
>>> print('%s is Not Unix %%'%name)
GNU is Not Unix %
Back to the original code, when you use _%_
, you are actually substituting the %r in the _='_=%r;print (_%%_)
with itself (again, treat _
as a var) and the %%
would result in a %
because the first one is treated as escape character and finally you are printing the whole result, so you would end up with:
_='_=%r;print (_%%_) ';print (_%_)
which is the exact replica of what produced it in the first place i.e. a quine.