_='_=%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 to commands in a line, so the following:is equivalent to:
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:
%suses a string,%ruses any object and converts the object to a representation through therepr()function.Now imagine you want to print a
%as well; a string such asGNU is Not Unix %. If you try the following,You will end up with a
ValueError, so you would have to escape the%with another%:Back to the original code, when you use
_%_, you are actually substituting the %r in the_='_=%r;print (_%%_)with itself 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:which is the exact replica of what produced it in the first place i.e. a quine.